我有一个 reducer ,它的数据属性是对象数组。也就是说,基本上:
state.data[0] = {id: 1,name: 'joe',tired=true}
state.data[1] = {id: 2,name: 'linda',tired=false}
etc.
我发现在我的 reducer 中,如果我想让琳达不累,我必须深入挖掘以迫使 react “不同”引擎识别发生了状态变化。正如您通过下面的代码所看到的,我实际上已经创建了对所有内容的新引用。
有没有更简单的方法来做到这一点?我希望我能理解 diff 如何更好地工作,以便当我将给定行的属性 Tired 设置为 true 时,我的对象会被渲染。感觉就像我正在击败一切。
const idToUpdate = 2;
newState = Object.assign({}, state);
let newData = [];
newState.data.map(function(rec){
if (rec.id === idToUpdate) {
rec.interestLevel = 998;
newData.push(rec);
} else {
newData.push(rec);
}
});
newState.data = newData;
最佳答案
如果你知道要更新的 id 并且假设你有一个对象数组,那么你可以执行类似的操作
const {data} = this.state;
const arr = data;
const Linda = arr.filter(item => item.id === idToUpdate)
var TiredLinda = Linda.map(item => return {id:item.id, name:item.name, tired:true}
//Now remove Linda from the original array
arr.filter(item => item.id !== idToUpdate)
//Now we will push the updated Linda to arr to replace the one we removed
arr.push(TiredLinda);
现在您想要设置数据的状态
this.setState({data:arr});
关于javascript - 如何简化这个react-redux reducer 状态变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49268170/