简体   繁体   中英

React - How to pass props via react-router v4 from one page to another?

I want to pass props not from parent to child but from one page to another using react router. I wasn't sure its even possible but found a few articles/posts here where it does seem possible. Based on what read my code should work, but it doesn't. Could anyone help?

index.jsx:

ReactDOM.render(<HashRouter><App /> </HashRouter>,document.getElementById('app'))

App.jsx:

class App extends React.Component {
  render (){
    return (
      <div>           
        <Switch history={browserHistory}>
          ...
          <Route exact path='/home/step1' component={Component1}/>
          <Route exact path='/home/step2' component={Component2}/>
        </Switch>
      </div>
    )
  }
}
...
import { Switch, Route, browserHistory} from 'react-router-dom'

My 2 components

import { Link, browserHistory } from 'react-router-dom';
export default class Component1 extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      id: undefined
    }
    this.navigateToStep2=this.navigateToStep2.bind(this);
  }
  navigateToStep2(e){
    e.preventDefault();
    browserHistory.push({pathname: "/home/step2", state:{id: this.state.id}})
  }
}

import { Link, browserHistory } from 'react-router-dom';
export default class Component2 extends React.Component {

render(){
  return (
    <div>
      <h1>hello: {this.props.id}</h1>
    </div>
  )
}

What I also tried is:

this.context.router.push({
  pathname: '/home/step2',
  state: {providerId: this.state.providerId}
})

This doesn't work as well but as I understand its because of router 4, I must use history browser now?

Im not sure if that is the best answer but I just found out how to do it:

Instead of pushing anything, I just put it insight my Link to the other page:

<Link to={{
     pathname: '/home/step2',
     state: { id: this.state.id }
     }}>GO
</Link>

then insight my other page, I can easy access it:

<h1>{this.props.location.state.id}</h1>

I still wonder why using browserHistory.push ... could make sense here, so if anyone know, it would be nice to know!

1) But this line

<Switch history={browserHistory}>

are you sure about it? History should be provided to your router context provider (HashRouter in your case)

2) Then, this line

browserHistory.push({pathname: "/home/step2", state:{id: this.state.id}})

But surely you need to use withRouter hoc/decorator to access current history object, otherwise it cannot deal with the context where (I suppose) history state is kept. Or just use the Link component as mentioned in an answer above

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