React Router 4 - 在 Link 组件中传递状态

React Router 4 - passing state in Link component

React newb 在这里,我注意到当我将路由器 Link 组件的状态传递给另一个组件时,即:

<Link to={{ pathname: '/myPath', state: { foo: myVar } }}>Text</Link>

单击 Link 时加载 myPath,然后我可以通过键入 this.props.location.state.foo 访问 myVar。即使重新加载页面(浏览器刷新),myVar 也不会丢失并且仍然保持其值,这正是我想要的

我可以在我的应用程序中访问 myPath 的另一种方法是 this.props.history.push("/myPath")。我可以通过这种方式实现与 Link 组件完全相同的功能吗?

谢谢

尚未尝试,但从 document 开始,history.push 也接受可选状态对象:

push(path, [state]) - (function) Pushes a new entry onto the history stack

我会尝试 this.props.history.push('/myPath', { foo: myVar });