终极版; 通过combineReducers使用组合减速器时访问该州的其他部分

Mat*_*rds 15 javascript reactjs react-router redux

更新

感谢@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
})
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我想基于全局状态的另一部分来改变条目状态; 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
  }
}
Run Code Online (Sandbox Code Playgroud)

想到的其他一些方法;

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

其他有用的信息;

有问题的实施是Universal App,它受react-redux-universal-hot-examples的启发

相关的deps

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

我怎样才能实现这种或类似的行为?我是否以正确的方式思考这个问题?

Dom*_*nic 8

回到过去,在开发人员的事情变得简单之前,人们会听历史对象上的popstate事件;)

看起来行动所需的信息?

history.listen((error, nextRouterState) => {
 ...
 store.dispatch(routerDidChange(nextRouterState));
Run Code Online (Sandbox Code Playgroud)

和行动:

export function routerDidChange(state) {
  return {
    type: ROUTER_DID_CHANGE,
    payload: state
  };
}
Run Code Online (Sandbox Code Playgroud)

所以试试看action.payload.

但是你的switch语句正在使用action而不是action.type那里有一些可疑的东西..你不应该做action = {}任何一件事- 请参阅http://redux.js.org/docs/basics/Reducers.html