React issues 记录

24 阅读1分钟

combineReducers函数

react版本:18.3.1

redux中的combineReducers函数目的是合并多个reducer到一个对象中,最终返回一个函数,这样可以redux可以分模块开发,业务代码结构更加清晰 但是发现一个问题,当不同模块中的reducer代码中,在处理不同的数据使用相同的action.type值的时候,会导致不应该发生变化的store中的值重置为空 所以加一个简单的判断可以避免

// 自己实现下combineReducers方法
function djCombineReducers(reducers) {
  if (!(typeof reducers === "object" && reducers != null)) {
    throw new Error("combineReducers arguments must be object");
  }
  return function (state, action) {
    const result = {};
    let dirtyNum = 0;
    for (const key of Object.keys(reducers)) {
      const reducerFn = reducers[key];
      const moduleState = state ? state[key] : undefined;
      const newState = reducerFn(moduleState, action);
      if (newState !== moduleState) {
        dirtyNum++;
      }
      result[key] = newState;
    }
    if (dirtyNum > 1 && state) {
      console.error(`store 不同模块中的action的type为${action.type}有重复`);
    }
    if (dirtyNum === 0) {
      //没有值修改
      return state;
    }
    return result;
  };
}

当用了重复的action.type的值的时候,控制台输出错误,可根据自己需求是否修改