从 react-router-redux 获取当前位置

Posted

技术标签:

【中文标题】从 react-router-redux 获取当前位置【英文标题】:Get current location from react-router-redux 【发布时间】:2016-12-26 19:59:47 【问题描述】:

使用“react-router-redux”时如何获取当前位置?

这是routing 状态:


    routing: 
        locationBeforeTransition: 
            pathname: "/foo",
            search: "",
            hash: "",
            state: null,
            action: "PUSH",
            key: "e8jfk"
        ,
        query: null,
        $searchBase: 
            search: "",
            searchBase: ""
        
    

我可以清楚地以state.routing.locationBeforeTransition.pathname 访问当前位置,但名称“locationBeforeTransition”似乎是上一页位置,而不是当前位置。这是我的路由状态中唯一的属性似乎也很奇怪。我怀疑我做错了什么。

这是一个只有路由的简化reducer:

reducer.js

import  combineReducers, createStore, applyMiddleware, compose  from 'redux';
import  routerReducer, routerMiddleware  from 'react-router-redux';
import  browserHistory  from 'react-router';
import thunkMiddleware from 'redux-thunk';

const reducer = combineReducers( 
  routing: routerReducer, 
);

export const store = createStore(reducer, , compose(
    applyMiddleware(
      routerMiddleware(browserHistory), 
      thunkMiddleware
    ),
    window.devToolsExtension ? window.devToolsExtension() : f => f
  )
);

【问题讨论】:

【参考方案1】:

您实际上无法从 redux 商店中获取它,因为根据 How do I access router state in a container component? 中的 react-router-redux 文档:

您不应该直接从 Redux 存储中读取位置状态。 这是因为 React Router 是异步操作的(处理事情 例如动态加载的组件)并且您的组件树可能不会 尚未与您的 Redux 状态同步更新。你应该依靠 由 React Router 传递的 props,因为它们只有在它拥有之后才会更新 处理所有异步代码。

【讨论】:

以上是关于从 react-router-redux 获取当前位置的主要内容,如果未能解决你的问题,请参考以下文章

无法读取未定义的属性“类型”(react-router-redux)

如何避免重定向两次(react-router-redux)?

在 react + redux + react-router-redux 中导航到用户登录成功的主页

react-router-redux 打破了我的应用程序状态

混淆 react-router-dom 和 react-router-redux

React-router-redux 推送操作不起作用