react 如何获得上一次访问的路由路径?

routes = {
    path: '/p',
    indexRoute: {component: A},
    childRoutes: [
        {
            path: '/p/listA',
            component: A
        },
        {
            path: '/p/listB',
            component: B
        },
        {
            path: '/p/detail,
            component: C
        }
    ]
}

比如说从A或者B跳转到了C,
如何实现在C准确获得A或B的路由路径,
C与AB组件之间没有父子关系

阅读 24k
6 个回答

谢邀~

跳转的话, 可以在接收页面的href中传参, 比如

http://www.baidu.com?参数名=地址

解析:

function GetQueryString(str) {
    var result = new RegExp("(^|)" + str + "=([^\&]*)(\&|$)", "gi").exec(LocString), tmp;
    if (tmp = result) { return tmp[2] };
    return "";
}

不需要那么复杂吧,如果只需要获取上一页来源,原生api就行了啊

console.log(document.referrer)
<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 })
    }
  }
})

我理解你的需求,需要记录上一次的history。但是实现起来有些繁琐。

思路是在一个“每次Router变化都可以得到callback的地方,将修改至记录下来”

如果使用react-router的话,在router.run()可以得到每次路由变化的callback,在这里将本次路由记录下来

然后就可以获取到了,当然还要做一些去重操作,比如重复刷新。

不好意思,来晚了,如果你是需要获得跳转过来的路径,或者路径带来的参数,来做别的事情的话,我建议,你往你的项目里面加入react-router
图片描述

图片描述

图片描述

图片描述

location 和 params就是你想要的参数,以及路由的路径了

具体的你还可以参考这个
https://github.com/ReactTrain...
这个是文档,以及一些的例子,你可以参考一下,对路径的优化以及获取会非常的方便
希望对你有帮助

推荐问题
宣传栏