【问题标题】:How to correctly return array in redux state, if the array did not have to be updated in the reducer?如果数组不必在reducer中更新,如何正确返回redux状态的数组?
【发布时间】:2021-05-03 08:40:05
【问题描述】:

我正在使用aurelia-store 状态管理库来管理状态。这个问题不是针对 Aurelia 商店的,实际上是针对一般的 redux 最佳实践,因为 Aurelia 商店非常相似。

我有一个从 API 获取单元更新的操作,如下所示:

export const fetchNewUnits = async (state: State): Promise<State> => {
  const fetchedUnits = await apiClient.getUnitsMarkers();

  // no new updates so don't trigger change in units
  // IS THIS ACCEPTABLE?
  if (fetchedUnits.length === 0) {
    return {
      ...state,
      highwaterMark: new Date()
    };
  }

  const units: UnitMarker[] = state.units.slice();

  _.forEach(fetchedUnits, (newUnit) => {
    // look for matching unit in store
    const idx = _.findIndex(units, {
      imei: newUnit.imei
    });

    // unit was found in store, do update
    if (idx !== -1) {
      // replace the unit in the store
      const replacement = new UnitMarker({...newUnit});
      units.splice(idx, 1, replacement);
    }
  });

  // OR SHOULD I ALWAYS DEEP COPY THE ARRAY REFERENCE AND IT'S OBJECTS
  return {
    ...state,
    highwaterMark: new Date(),
    units: [...units]
  };
};

如果我没有任何单位更改(即我的商店是最新的),我可以简单地使用扩展运算符返回状态,如第一个返回语句中所示?因为我没有修改对象,这很好吗?

或者我是否总是需要进行深度替换,例如:

return {
    ...state,
    highwaterMark: new Date(),
    units: [...state.units]
  };

即使数组中的对象没有改变?

【问题讨论】:

    标签: redux react-redux aurelia immutability aurelia-store


    【解决方案1】:

    你应该创建一个新对象的原因是因为 React 组件会检查 prop 更改以了解何时重新渲染。 如果你只是简单地修改一个对象并再次将其作为 props 传入,React 将不知道发生了什么变化并且无法重新渲染。

    所以在您的情况下,问题是:您是否要重新渲染?如果你不这样做,返回同一个对象就可以了,一个简单的“返回状态”会让 React 知道不需要重新渲染。

    见:Why is the requirement to always return new object with new internal references

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-05
      • 2020-06-14
      • 2017-03-26
      • 2019-02-03
      • 2016-07-02
      • 1970-01-01
      • 2019-05-07
      • 2020-01-28
      相关资源
      最近更新 更多