【问题标题】:Redux; accessing other parts of the state when using composed reducers via combineReducers还原;通过 combineReducers 使用组合减速器时访问状态的其他部分
【发布时间】:2015-11-19 13:18:12
【问题描述】:

更新

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

正确答案当然是;

所以尝试检查action.payload

关于 switch 语句和我们所指的动作对象的其他 cmets 是我在示例中犯的错误,我已经更正了这些错误。


假设我已经组合了以下两个减速器;

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 方法中查询路由器状态

其他有用的信息;

有问题的实现是受 react-redux-universal-hot-example 启发的 Universal App

相关部门

  • 反应 0.14.2
  • redux 3.0.3
  • 反应路由器 1.0.0-rc3
  • redux-router 1.0.0-beta3

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

【问题讨论】:

  • Actions 是一个类型的对象和一个可选的负载。正如@Dominic Tobias 所提到的,您应该打开动作的 type 属性并将路由作为有效负载发送到减速器。

标签: javascript reactjs react-router redux


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-04-11
    • 1970-01-01
    • 2017-07-03
    • 2018-07-09
    • 2016-07-25
    • 2019-04-20
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多