简体   繁体   中英

How to pass props to nested routes in React Router 4?

I have a component tree like this:

-App
--UserList
---UserItem
---UserItem
---UserItem
--User

I'm not being able to pass user data from UserItem to User . This is what I have:

App.js

export default class App extends Component {
  state = { users: [] }

  componentDidMount() {// fetch and setState}

  render() {
    return (
      <BrowserRouter>
        <Route
          exact
          path="/"
          render={() => <UserList users={this.state.users} />}
        />
      </BrowserRouter>
    )
  }

}

UserList.js

export default function({ users }) {
  return (
    <div>
      {users.map(user => (
        <UserItem user={user} key={`${user.id}`} />
      ))}
    </div>
  )

}

This is where the problem is: I want to pass the data from the parent component to the child User component, instead of having to fetch the user data from the API again.

UserItem.js

export default function({ user }) {
  return (
    <div>
      <Link to="/user">{user.name}</Link>

      <Route path={`/user/${user.name}`} render={() => <User user={user} />} />
    </div>
  )
}

I'm not sure what you're trying to implement here. Your app renders the UserList when then route is / . The UserList renders a UserItem component for each user in the array. Each UserItem simply renders a route specific to every user, which will render the User component if that route is triggered.

But if I'm not mistaken, the UserList will not be rendered if the route is anything but / , so if someone accesses user/... , the inner routes won't actually exist.

Essentially, this app will not render anything.

If you remove the exact keyword from the route in App , I think you'll get the result you are looking for. In this case, opening /user/<USER_NAME> will render the User element for that user.

Your question is regarding passing props into a component through a route, and the mechanism you've used is correct.

<Route path={...} render={() => <User user={user} />} />

This is actually right. See the code linked below. On changing the route to /user/User1 , you'll see the name of "User1" rendered in the app.

See the working code here: https://codesandbox.io/s/18w3393767

您应该在UserItem组件中使用this.props.users

我不确定,但是您可以通过以下道具吗?在这里,我通过道具进行渲染,然后传递给用户组件

      <Route path={`/user/${user.name}`} render={(props) => <User user={user} {...props} />} />
export default function({ users }) {
  return (
    <div>
      { this.props.users.map(user => ( 
    //mistake here this.props.users.map not users.map 
        <UserItem user={user} key={`${user.id}`} />
      ))}
    </div>
  )

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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