如何使用反应路由器获取以前的位置?
How to get previous location with react router?
我正在尝试从 React 路由器获取之前的位置。我已经设置了一个 reducer 来监听 @@router/LOCATION_CHANGE 并存储当前位置和新位置,但是这个动作似乎不再被触发了?
Reducer 看起来像这样:
const initialState = {
previousLocation: null,
currentLocation: null,
};
const routerLocations = function (state = initialState, action) {
const newstate = { ...state };
switch (action.type) {
case "@@router/LOCATION_CHANGE":
newState.previousLocation = state.currentLocation;
newState.currentLocation = action.payload;
return newState
default:
return state;
}
}
export default routerLocations;
@@router/LOCATION_CHANGE 是正确的倾听方式吗?
我正在使用
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-router-redux": "^4.0.8",
最好像这样直接从react-router-redux
导入动作类型:
import { LOCATION_CHANGE } from 'react-router-redux'
然后在你的reducer中使用它。此操作 return 新对象 history
更改后。可能,您只需要 pathname
属性。
所以,你的reducer应该是这样的:
import { LOCATION_CHANGE } from 'react-router-redux'
const initialState = {
previousLocation: null,
currentLocation: null,
}
export default (state = initialState, action) => {
switch (action.type) {
case LOCATION_CHANGE:
return {
previousLocation: state.currentLocation,
currentLocation: action.payload.pathname,
}
default:
return state
}
}
我遇到了这个动作在初始渲染时没有触发的问题。我已经调查并意识到它只能用于 history
早于 v4.0.0-2 的版本。
这与react-router-redux
的内部实现有关。在库的底层,在初始渲染 getCurrentLocation
期间调用 history
对象,该对象已在历史版本 v4.0.0-2 中删除。
这就是为什么您应该降级 history
版本或尝试订阅 history
更改并在初始渲染时自行调度操作。
我正在尝试从 React 路由器获取之前的位置。我已经设置了一个 reducer 来监听 @@router/LOCATION_CHANGE 并存储当前位置和新位置,但是这个动作似乎不再被触发了?
Reducer 看起来像这样:
const initialState = {
previousLocation: null,
currentLocation: null,
};
const routerLocations = function (state = initialState, action) {
const newstate = { ...state };
switch (action.type) {
case "@@router/LOCATION_CHANGE":
newState.previousLocation = state.currentLocation;
newState.currentLocation = action.payload;
return newState
default:
return state;
}
}
export default routerLocations;
@@router/LOCATION_CHANGE 是正确的倾听方式吗?
我正在使用
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",
"react-router-redux": "^4.0.8",
最好像这样直接从react-router-redux
导入动作类型:
import { LOCATION_CHANGE } from 'react-router-redux'
然后在你的reducer中使用它。此操作 return 新对象 history
更改后。可能,您只需要 pathname
属性。
所以,你的reducer应该是这样的:
import { LOCATION_CHANGE } from 'react-router-redux'
const initialState = {
previousLocation: null,
currentLocation: null,
}
export default (state = initialState, action) => {
switch (action.type) {
case LOCATION_CHANGE:
return {
previousLocation: state.currentLocation,
currentLocation: action.payload.pathname,
}
default:
return state
}
}
我遇到了这个动作在初始渲染时没有触发的问题。我已经调查并意识到它只能用于 history
早于 v4.0.0-2 的版本。
这与react-router-redux
的内部实现有关。在库的底层,在初始渲染 getCurrentLocation
期间调用 history
对象,该对象已在历史版本 v4.0.0-2 中删除。
这就是为什么您应该降级 history
版本或尝试订阅 history
更改并在初始渲染时自行调度操作。