【问题标题】:Accessing a Redux store value from a reducer without control over the action creator从 reducer 访问 Redux 存储值,而不控制 action creator
【发布时间】:2017-11-08 02:55:28
【问题描述】:

我处于一种不寻常的情况: 在页面加载时,假设我的 Redux 存储使用基本值进行补充:

{ foo: true }

在reducer 中,我使用react-router-redux(或任何其他自行调度动作的库,只提供对动作类型的访问权限)来更新LOCATION_CHANGE 类型动作的状态:

...
case LOCATION_CHANGE: {
  const deserialized = deserialize(action.payload.query, **foo**);
  return { ...state, deserialized };
}
...

我的deserialize 函数需要foo 的值来相应地更新我的状态。通常,我会将getState().foo 添加到我的操作负载中,但由于这是一个第三方库,我不控制操作负载。对于这个问题,是否有不需要我删除第三方库的简单解决方法?

【问题讨论】:

    标签: javascript redux react-router-redux


    【解决方案1】:

    是的,使用 Redux 中间件来转换操作。

    你可能想看看some of the existing middleware for intercepting and modifying dispatched actions

    【讨论】:

      【解决方案2】:

      我接受了 markerikson 的 answer,但这是我最终编写的中间件:

      const locationChangeMiddleware = store => next => action => {
        if (action.type === LOCATION_CHANGE) {
          const { foo } = store.getState();
          return next({
            ...action,
            payload: {
              ...action.payload,
              foo,
            },
          });
        }
      
        return next(action);
      };
      

      现在我的减速器看起来像:

      ...
      case LOCATION_CHANGE: {
        const deserialized = deserialize(action.payload.query, action.payload.foo);
        return { ...state, deserialized };
      }
      ...
      

      【讨论】:

        猜你喜欢
        • 2019-02-21
        • 1970-01-01
        • 2017-09-28
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        • 1970-01-01
        • 2020-08-17
        • 1970-01-01
        相关资源
        最近更新 更多