React router, pass data when navigating programmatically?

前端 未结 6 1265
广开言路
广开言路 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 12:51

    Passing query parameters when programatically navigation in react router

    History objects may be used programmatically change the current location using both history.push and history.replace.

        history.push('/home?the=query', { some: 'state' })
    

    If we pass the history object down into a component as props. Then we can navigate programatically using the react router methods available on the history object.

    Now lets assume you are passing down the history object as a prop called 'router'. So it would be referenced inside a component with class based syntax like:

    this.props.router
    

    When using push or replace you can either specify both the URL path and state as separate arguments or include everything in a single location-like object as the first argument.

    this.props.router.push('/some/path?the=query')
    

    Or you can use a single location-like object to specify both the URL and state. This is equivalent to the example above.

    this.props.router.push({
      pathname: '/some/path',  //path
      search: '?the=query' // query param named 'search'
    })
    

    Note - Of course make sure that the this.props.router is actually the history object from the react-router api.

提交回复
热议问题