2016-08-19 106 views
3

如何在使用“react-router-redux”时获取当前位置?从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.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 
) 
); 

回答

3

你不能真正得到从Redux的商店,因为根据反应 - 路由器 - REDO文档How do I access router state in a container component?

您不应直接从Redux存储中读取位置状态。 这是因为React路由器异步操作(处理动态加载组件等东西 ),而您的组件树可能不是 还与您的Redux状态同步更新。您应该依赖React Router传递的 道具,因为它们只有在 处理完所有异步代码后才会更新。