React router, pass data when navigating programmatically?

前端 未结 6 1260
广开言路
广开言路 2020-12-07 12:06

We could navigate to different path using

this.props.router.push(\'/some/path\')

Is there a way to send params (object) along when navigating?

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 13:05

    React Router uses location objects. One of the properties of a location object is state.

    this.props.router.push({
      pathname: '/other-page',
      state: {
        id: 7,
        color: 'green'
      }
    })
    

    On the page that is navigated to, the current location will be injected into the component whose route matched, so you can access the state using this.props.location.state.

    One thing to keep in mind is that there will be no state if a user navigates directly to the page, so you will still need some mechanism to load the data when it does not exist.

提交回复
热议问题