我刚刚改变了这个

const newCities = {...newState.cities};
newCities[action.payload.id] = action.payload;
newState.cities = newCities;


一线

newState.cities = {...newState.cities, [action.payload.id]: action.payload};


但是我该如何改变

const newCities = {...newState.cities};
action.payload.forEach(city=> newCities[city.id] = city);
newState.cities = newCities;


一线吗? ~~

newState.cities = {...newState.cities, action.payload.map(city=> [city.id]: city)};

最佳答案

最终解决方案:

newState.cities = {...newState.cities, ...action.payload.reduce((o,a)=> ({...o,[a.id]:a}),{})};


以前我忘了初始化reduce array =)

旧方法:
可能是这样吗?

newState.cities = {...newState.cities, ...action.payload.map(city=> ({[city.id]: city}) )};


更新:

newState.cities = {...newState.cities, ...action.payload.reduce(city=> ({[city.id]:city}) )};


更新(完全丑陋):

newState.cities = {...newState.cities, ...action.payload.map((o)=> ({[o.id]:o}) ).reduce((o,a)=>({...o,...a}))};

关于javascript - 传播具有多个变化的特性:一线式ECMA不变性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42110913/

10-12 01:00