reactjs - 如何使用 react 路由器获取以前的位置?

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

我正在尝试从 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 中使用它。此操作在 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 更改并在初始渲染时自行分派(dispatch)操作。

关于reactjs - 如何使用 react 路由器获取以前的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49982230/

相关文章:

javascript - react native : How to add variables inside View?

reactjs - 以编程方式导航到不同的路线

reactjs - TypeScript react : RouteComponentProps types error or cant access history

reactjs - 使用查询字符串触发 Redux/React Router 中的操作

javascript - 在组件中处理通过 react-router 传递的参数

css - React maskImage 内联不起作用 - 与 backgroundImage 相同的图像

javascript - React.js 获取 Giphy API

javascript - 在 React Native 中搜索 FlatList

javascript - 为什么 redux 每次更改时都需要复制数据?

javascript - 为什么 Redux 不将我的操作分派(dispatch)给 reducer ?