【问题标题】:How to get previous location with react router?如何使用反应路由器获取以前的位置?
【发布时间】:2018-10-03 13:36:21
【问题描述】:

我正在尝试从反应路由器获取以前的位置。我已经设置了一个减速器来监听@@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",

【问题讨论】:

    标签: reactjs react-redux react-router-v4 react-router-dom


    【解决方案1】:

    最好像这样直接从react-router-redux导入动作类型:

    import { LOCATION_CHANGE } from 'react-router-redux'
    

    然后在你的减速器中使用它。 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 的内部实现有关。在库的底层,在初始渲染期间,history 对象的 getCurrentLocation 被调用,这在历史版本 v4.0.0-2 中已被删除。

    这就是为什么您应该降级 history 版本或尝试订阅 history 更改并在初始渲染时自行调度操作。

    【讨论】:

    • 谢谢!订阅历史更改对我有用。
    • "这个项目不再维护。为了你的 Redux 路由器同步需求与 React Router 4+"
    猜你喜欢
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多