【问题标题】:Updating isLoading field on a redux store在 redux 存储上更新 isLoading 字段
【发布时间】:2017-03-29 09:02:52
【问题描述】:

我的微调器表明我的应用正在加载。我的应用程序中的许多减速器需要能够将此加载器设置为 true 或 false。

我的假设: 该字段需要位于状态树的最顶层。我们就叫它isLoading吧。

问题: Redux reducer 更新他们自己的状态树部分。有哪些方法可以构建我的 reducer 以更新最顶层的 isLoading 字段?

我对@9​​87654323@ 很熟悉,但是在每个操作上分派一个事件似乎有点矫枉过正。但也许我错了,这是正确的方法。此外,我当然有可能错误地设计了我的状态树。

作为参考,我目前正在使用 redux thunk:

export const fetchAssets = () => {
  return dispatch => {
    request
      .get('http://myapi.com/assets')
      .set('Accept', 'application/json')
      .end(function(err, res){
        if (err) {
          return dispatch(fetchAssetsFailure(err));
        }
        dispatch(fetchAssetsSuccess(res.body.data));
      });
  }
}

【问题讨论】:

    标签: javascript reactjs redux redux-thunk


    【解决方案1】:

    Reducer 接收所有已调度的操作,因此您希望您的 isLoading reducer 对每个相关操作做出反应,而不是其他 reducer 设置此值。显然,你不能使用action.type,因为你无法预测所有相关的动作,它会创建一个非常麻烦的reducer。你可以做的是在动作中添加另一个字段,这个 reducer 会对该字段做出反应。

    示例动作创建者:

    const createSampleAction = (payload, isLoading) => ({
        type: 'SAMPLE_ACTION',
        payload,
        meta: {
            isLoading
        }
    });
    

    还有减速机:

    const isLoadingReducer = (state = false, { meta }) => {
      const isLoading = meta && meta.isLoading;
    
      if (isLoading !== undefined) {
          return isLoading;
      }
    
      return state;
    }
    

    如果您对使用 meta 而不是 action 类型的 reducer 不满意,您可以创建一个中间件,该中间件将执行相同的属性来调度 showLoading / hideLoading 操作,并且 reducer 将对这些操作做出反应:

    const isLoadingMiddleware = ({ dispatch }) => next => {
      next(action);
      const isLoading = action.meta && action.meta.isLoading;
    
      if (isLoading !== undefined) {
          dispatch(isLoading ? showLoading () : hideLoading());
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-02-26
      • 1970-01-01
      • 2018-10-02
      • 2022-01-06
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2018-07-16
      • 2020-10-15
      相关资源
      最近更新 更多