2016-08-19 95 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傳遞的 道具,因爲它們只有在 處理完所有異步代碼後纔會更新。