【问题标题】:How do I listen for react-router location change in redux reducer?如何在 redux reducer 中监听 react-router 位置变化?
【发布时间】:2016-10-28 20:19:16
【问题描述】:

我有一个 React Redux 应用程序,并试图在我的一个 reducer 中监听 react-router 位置变化。我使用的是hashHistory,而不是browserHistory。在我的 Redux devtools 中,我可以看到它在位置更改时触发了一个动作:

但是,在我的减速器中,当我侦听“LOCATION_CHANGE”时,它什么也捕捉不到。

import * as types from '../constants/actionTypes';
import objectAssign from 'object-assign';
import initialState from './initialState';

export default function listingsReducer(state = initialState.listings, action) {
  switch (action.type) {
    case 'LOCATION_CHANGE': {
        console.log(action); //currently doesn't get into this case block
        return state;
    }
    default:
        return state;
  }
}

我必须使用什么来在我的 reducer 中处理此操作?

【问题讨论】:

    标签: javascript reactjs redux react-router


    【解决方案1】:

    case 'LOCATION_CHANGE' 更改为case '@@router/LOCATION_CHANGE'

    【讨论】:

      【解决方案2】:

      更好的是,使用react-router提供的常量:

      import { LOCATION_CHANGE } from 'connected-react-router';
      
      // ...
      
      switch (action.type) {
          case LOCATION_CHANGE: {}
      }
      

      【讨论】:

      • 问题--LOCATION_CHANGE 是 React-Router 还是 Connected-React-Router 提供的常量?此外,我还没有找到关于这个常数的任何实际文档。知道为什么吗?
      • 肯定来自connected-react-router (github.com/supasate/connected-react-router/blob/master/src/…) 并且文档可能有点缺乏。但既然这是命名 redux 动作的标准方式,也许他们认为没有必要。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 2019-08-07
      • 2021-07-02
      • 1970-01-01
      • 2019-11-01
      • 2021-07-13
      相关资源
      最近更新 更多