我有一个应用程序,在其中映射了一些示例用户组件。我添加了一些道具,我想建立一个条件导航链接,该链接仅呈现一个显示名称的简单“配置文件”组件。
到目前为止,我已经进行了条件导航,在组件内部进行了链接,并且道具正确发送,并且在我的User组件下显示了该段落,但是我想使其重定向,因此它仅显示Profile组件。
有没有办法让它仅显示该组件。我尝试使用该开关,但我意识到,它仅呈现第一个路线,因此其他所有内容仍将显示...
render() {
let persons= this.state.persons.map((item, index) =>{
return(
<Router>
<User key={index} name={item.name} img={item.img} id={item.id} />
</Router>
)
})
//user component
render(){
console.log(this.props.name)
return(
<Switch>
<div >
<img src={this.props.img} alt="profile" style={{float: 'left'}}>
</img>
<p style={{textAlign: 'center'}}>{this.props.name}</p>
<p>It's here={this.props.loggedInProp}</p>
<Route path="/:username" exact component={ Profile} />
<NavLink to={`/${this.props.name}`}>Click me</NavLink>
</div>
</Switch>
//Profile component
const Profile= ({match}) =>{
return(
<div>
<p>Hello {match.params.username}</p>
</div>
)
}
答案 0 :(得分:1)
<Route
exact
path="/profile/view/:username"
render={props => <ProfileView {...props} />}
/>
然后在ProfileView组件内部,您可以使用this.props.match.params.username
过滤数据集并仅显示其详细信息。
ProfileView组件
import React, { Component } from 'react';
export class ProfileView extends Component {
constructor(){
super()
this.state = {
allUsers[{ user1 ... }, {user2 ...}, ...],
selectedUser: {}
}
}
componentDidMount(){
// fetch('/get/users/from/somewhere').then(users => {
// this.setState({allUsers: users}) // Usually you would just pull your one user from the route and then fetch it's single details from a database
// })
this.setState({selectedUser: allUsers.filter(user => user.username === this.props.match.params.username)})
}
render() {
return (
<div>
<em>Do stuff with your this.state.selectedUser... things here</em>
</div>
);
}
}