简体   繁体   中英

Can I pass some content via react-router-4's history.push?

How can I pass some info by react-router-4 's history push method?

  • render a list of users
  • when click the user I wanna direct to the new url and pass the specific user info
  • then render the user base on the passed in user info

when I think about this, another question came up, if I can pass the user info where does React keep the user's info?

<List>
  {users.map(user =>
    <ListItem
      key={user.id}
      thumb={use.img}
      arrow="horizontal"
      onClick={() => this.handleUserClick(user)}
     >
      {user.nickname}
    </ListItem>
  )}
</List>
handleUserClick = (user) => {this.props.history.push(`/user/${user.id}`)}

You can pass some state with history's push

handleUserClick = (user => {
    this.props.history.push(`/user/${user.id}`, {userName: 'Bob'}); 
})

And then you can access the history from your component

const User = ({history}) => <span>Hello {history.location.state.userName}</span>

This should show "Hello Bob"

Don't abuse this though and prefer to keep the state either in a parent react component or by using a library like redux or mobx if your application gets more complex.

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