我用的是反应路由器。我想从我来自的地方检测上一个页面(在同一个应用程序中)。我的上下文中有路由器。但是,我看不到路由器对象上的任何属性,比如“前一条路径”或历史记录。我该怎么做呢?
发布于 2016-09-02 10:11:28
可以在componentWillReceiveProps生命周期方法中保存以前的路径。逻辑非常接近故障排除部分 of react-router docs中提供的示例。
<Route component={App}>
{/* ... other routes */}
</Route>
const App = React.createClass({
getInitialState() {
return { prevPath: '' }
},
componentWillReceiveProps(nextProps) {
if (nextProps.location !== this.props.location) {
this.setState({ prevPath: this.props.location })
}
}
})最近,从州访问它。
发布于 2018-05-01 02:22:12
您可以使用<Link>组件传递状态,在本例中为路径名:
<Link to={{pathname: '/nextpath', state: { prevPath: location.pathname }}}>Example Link</Link>然后,您可以在下一个组件中从prevPath访问this.props.location.state。
发布于 2020-08-06 04:01:42
与其检查前一页是什么,不如从另一个角度来处理问题。将当前页面作为支持传递到要导航到的组件或链接。
在我调用history.push或单击链接的上一页或组件中,我添加了当前页面的状态。
history.push(`/device/detail`, { from: 'device detail page' } );然后,我可以使用history.location.state.from访问上一页的内容。
https://stackoverflow.com/questions/39288915
复制相似问题