我使用aurelia-store状态管理库来管理状态。这个问题并不是专门针对Aurelia商店的,而是因为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]
};即使数组中的对象没有改变?
发布于 2021-01-31 04:06:21
之所以要创建一个新对象,是因为React组件会检查正确的更改,以便知道何时重新渲染。如果你只是简单地修改一个对象,并再次将其作为一个道具传递进来,React将不会知道某些东西发生了变化,并且将无法重新呈现。
因此,在您的情况下,问题是:您是否想要重新渲染?如果你不这样做,返回相同的对象是很好的,一个简单的“返回状态”会让React知道不需要重新渲染。
请参阅:Why is the requirement to always return new object with new internal references
https://stackoverflow.com/questions/65954274
复制相似问题