[英]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:索引.jsx:
ReactDOM.render(<HashRouter><App /> </HashRouter>,document.getElementById('app'))
App.jsx:应用程序.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我的 2 个组件
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?这不起作用,但据我了解,由于路由器 4,我现在必须使用历史浏览器吗?
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!我仍然想知道为什么使用 browserHistory.push ......在这里可能有意义,所以如果有人知道,很高兴知道!
1) But this line 1)但是这条线
<Switch history={browserHistory}>
are you sure about it?你确定吗? History should be provided to your router context provider (HashRouter in your case)
历史记录应提供给您的路由器上下文提供程序(在您的情况下为 HashRouter)
2) Then, this line 2)然后,这一行
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.但是您肯定需要使用
withRouter
hoc/decorator 来访问当前历史对象,否则它无法处理(我想)保留历史状态的上下文。 Or just use the Link
component as mentioned in an answer above或者只使用上面答案中提到的
Link
组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.