我正在使用React Router。我想检测我来自何处的上一页(在同一应用程序内)。我在上下文中拥有路由器。但是,我在路由器对象上看不到“上一条路径”或历史记录之类的任何属性。我该怎么做?
您可以在componentWillReceiveProps生命周期方法中保存先前的路径。该逻辑非常接近文档的疑难解答部分中提供的示例react-router。
componentWillReceiveProps
react-router
<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 }) } } })
最近,可以从州访问它。