小编典典

Redux; 通过CombineReducers使用组合化的reducer时访问状态的其他部分

reactjs

更新资料

感谢@Dominic Tobias和@gabdallah发现了我的尴尬错误。

正确的答案当然是正确的。

因此,请尝试检查action.payload

关于switch语句和action对象的其他注释,我们指的是我在示例中所做的错误,此后我已对其进行了纠正。


想象一下,我将以下两个减速器结合了起来;

import { combineReducers } from 'redux'
import { routerStateReducer } from 'redux-router'
import entries from './entries'

export default combineReducers({
  router: routerStateReducer,
  entries
})

在这种情况下,我想基于全局状态的另一部分来改变条目状态。redux-router提供的路由器状态,例如以实现分页。

我该怎么做?

// entries.js
import { ROUTER_DID_CHANGE } from 'redux-router/lib/constants'
const initialState = {}

function entries (state = initialState, action) {
  switch (action.type) {
    case ROUTER_DID_CHANGE:
      // How can I access `state.router` here in order to do something like this;
      if (routerState.location.pathname === '/entries') {
        return {
          ...state,
          page: routerState.location.query.page || state.page,
          limit: routerState.location.query.limit || state.limit
        }
      }
      return state
  }
}

我想到了其他一些方法;

  • 将路由器状态连接到Entries路由组件,使用componentWillMount生命周期方法检查路由器状态,并使用页面和限制值依次更改条目状态来调用操作创建者。这会起作用;但是我在fetchData安装之前使用一些过渡中间件在路由组件上调用静态方法,因此获取了数据,然后将在以后调用分页动作创建器;不是期望的行为。
  • 收听其他地方的路由器操作(即专用的路由器redux模块),在条目存储中调用操作创建者,但是我不确定这与redux-router的匹配程度如何,或者我将如何访问该路由器的路由器部分全球商店。
  • 完全不要这样做;只需在静态fetchData方法中查询路由器状态

其他有用的信息;

所讨论的实现是Universal App在很大程度上受react-redux-universal-hot-example的启发

相关部门

  • 反应0.14.2
  • Redux 3.0.3
  • react-router 1.0.0-rc3
  • redux-router 1.0.0-beta3

我怎样才能达到这种或类似的行为?我什至在想这是正确的方法吗?


阅读 240

收藏
2020-07-22

共1个答案

小编典典

早在对开发人员来说事情变得更简单之前,人们会听取历史对象上的popstate事件;)

看起来所需的信息正在执行中?

history.listen((error, nextRouterState) => {
 ...
 store.dispatch(routerDidChange(nextRouterState));

和动作:

export function routerDidChange(state) {
  return {
    type: ROUTER_DID_CHANGE,
    payload: state
  };
}

因此,请尝试检查action.payload

但是,您的switch语句正在使用action而不是,action.type所以这里有些混乱。.您也不需要执行action = {}任何操作-
请参阅http://redux.js.org/docs/basics/Reducers.html

2020-07-22