简体   繁体   English

在redux商店上更新isLoading字段

[英]Updating isLoading field on a redux store

I have spinner that indicates my app is loading. 我有微调器,表明我的应用程序正在加载。 Many reducers in my app need to be able to set this loader to either true or false. 我的应用程序中的许多reducer需要能够将此加载程序设置为true或false。

My Assumption: This field needs to live on the top most level of the state tree. 我的假设:此字段需要位于状态树的最顶层。 Let's call it isLoading . 我们称之为isLoading

The Problem: Redux reducers update their own portion of the state tree. 问题: Redux reducer更新状态树的部分。 What are some ways I can structure my reducers to update the isLoading field on the top most level? 有什么方法可以构建我的reducer来更新最高级别的isLoading字段?

I am familiar with redux-thunk but it seems like a bit of an overkill to dispatch an event on every action. 我熟悉redux-thunk但是在每个动作上发送一个事件似乎有点过分。 But maybe I'm wrong and that is the correct approach. 但也许我错了,这是正确的方法。 Also, it is certainly possible I am designing my state tree incorrectly. 此外,我当然有可能错误地设计我的状态树。

For reference, I am currently using redux thunk as such: 作为参考,我目前正在使用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));
      });
  }
}

Reducers receive all dispatched actions, so you want your isLoading reducer to react to every relevant action, instead of other reducers setting this value. Reducers接收所有已分派的操作,因此您希望isLoading reducer对每个相关操作做出反应,而不是设置此值的其他reducers。 Obviously, you can't use the action.type since you can't predict all relevant actions, and it will create a very cumbersome reducer. 显然,你不能使用action.type因为你无法预测所有相关的动作,它会创建一个非常麻烦的减速器。 What you can do is add another field to the action, and this reducer will react to that field. 您可以做的是向操作添加另一个字段,此减速器将对该字段做出反应。

Sample action creator: 示例动作创建者:

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

And the reducer: 还原剂:

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

  if (isLoading !== undefined) {
      return isLoading;
  }

  return state;
}

If you're not comfortable with reducers that use the meta instead of the action type, you can create a middleware that will do the same property to dispatch showLoading / hideLoading actions, and the reducer will react to those actions: 如果您对使用元而不是操作类型的Reducer不满意,您可以创建一个中间件,它将执行相同的属性来调度showLoading / hideLoading操作,reducer将对这些操作做出反应:

const isLoadingMiddleware = ({ dispatch }) => next => {
  next(action);
  const isLoading = action.meta && action.meta.isLoading;

  if (isLoading !== undefined) {
      dispatch(isLoading ? showLoading () : hideLoading());
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM