检测反应路由器中的先前路径?

新手上路,请多包涵

我正在使用反应路由器。我想检测我来自的上一页(在同一个应用程序中)。我在我的上下文中有路由器。但是,我在路由器对象上看不到任何属性,例如“先前路径”或历史记录。我该怎么做?

原文由 vijayst 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 827
2 个回答

您可以将以前的路径保存在 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 })
    }
  }
})

最近,从状态访问它。

原文由 Alexandr Lazarev 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 <Link> 组件向下传递状态,在本例中为路径名:

 <Link to={{pathname: '/nextpath', state: { prevPath: location.pathname }}}>Example Link</Link>

然后,您可以在下一个组件中从 this.props.location.state 访问 prevPath

原文由 Sam Logan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进