从 react-router-redux 获取当前位置
Get current location from 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
)
);
你实际上无法从 redux 存储中获取它,因为根据 How do I access router state in a container component? 中的 react-router-redux 文档:
You should not read the location state directly from the Redux store.
This is because React Router operates asynchronously (to handle things
such as dynamically-loaded components) and your component tree may not
yet be updated in sync with your Redux state. You should rely on the
props passed by React Router, as they are only updated after it has
processed all asynchronous code.
使用"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
)
);
你实际上无法从 redux 存储中获取它,因为根据 How do I access router state in a container component? 中的 react-router-redux 文档:
You should not read the location state directly from the Redux store. This is because React Router operates asynchronously (to handle things such as dynamically-loaded components) and your component tree may not yet be updated in sync with your Redux state. You should rely on the props passed by React Router, as they are only updated after it has processed all asynchronous code.