Javascript 如何简化此react redux reducer状态更改

Javascript 如何简化此react redux reducer状态更改,javascript,reactjs,react-redux,Javascript,Reactjs,React Redux,我有一个reducer,它的数据属性是一个对象数组。就是基本上, state.data[0] = {id: 1,name: 'joe',tired=true} state.data[1] = {id: 2,name: 'linda',tired=false} etc. 我发现,在我的减速机中,如果我想让琳达不累,我必须深入挖掘,迫使反应“不同”引擎识别发生的状态变化。正如您从下面的代码中看到的,我实际上已经创建了一个对所有内容的新引用 const idToUpdate = 2;

我有一个reducer,它的数据属性是一个对象数组。就是基本上,

state.data[0] = {id: 1,name: 'joe',tired=true}
state.data[1] = {id: 2,name: 'linda',tired=false}
etc.
我发现,在我的减速机中,如果我想让琳达不累,我必须深入挖掘,迫使反应“不同”引擎识别发生的状态变化。正如您从下面的代码中看到的,我实际上已经创建了一个对所有内容的新引用

        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;
有没有更简单的方法?我希望我能更好地理解diff的工作原理,以便在为给定行将属性设置为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})