简体   繁体   English

映射组件时渲染条件路线

[英]Rendering conditional route, when mapping components

I have an application, where I map some sample user components. 我有一个应用程序,在其中映射了一些示例用户组件。 I add some props, and I want to make a conditional nav link, that renders just a simple "profile components that show the name. 我添加了一些道具,我想建立一个条件导航链接,该链接仅呈现一个显示名称的简单“配置文件”组件。

So far I have made a conditional nav, link inside the component, and the props get send correctly, and it displays the paragraph under my User component, but I want to make it redirect, so it only shows the Profile component. 到目前为止,我已经进行了条件导航,在组件内部建立了链接,并且道具正确发送,并且在我的User组件下显示了该段落,但是我想使其重定向,因此它仅显示Profile组件。

Is there a way so it only shows that component. 有没有办法让它只显示该组件。 I tried with the switch but I realized, that it only renders the first, route, so everything else, will still be shown... 我尝试使用开关,但我意识到,它仅呈现第一个路线,因此其他所有内容仍将显示...

 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>
)
}
<Route
    exact
        path="/profile/view/:username"
        render={props => <ProfileView {...props} />}
/>

inside of ProfileView component you could then use this.props.match.params.username to filter your collection of data and display only it's details. 然后,您可以在ProfileView组件内部使用this.props.match.params.username过滤数据集合并仅显示其详细信息。

ProfileView component 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>
     );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM