简体   繁体   English

如何简化React-Redux Reducer状态更改

[英]How to simplify this react-redux reducer state change

I've got a reducer that has a data attribute that is an array of objects. 我有一个reducer,它的data属性是对象数组。 That is, basically: 也就是说,基本上:

state.data[0] = {id: 1,name: 'joe',tired=true}
state.data[1] = {id: 2,name: 'linda',tired=false}
etc.

I've found that in my reducer, if I want to make linda not tired, I have to dig really deep to force the react "differ" engine recognize a state chage happened. 我发现在我的减速器中,如果我想让琳达不累,就必须深入挖掘以迫使反应“不同”的引擎识别出状态变化。 As you can see by the below code, I've practically create a new reference to everything. 从下面的代码中可以看到,我实际上已经创建了对所有内容的新引用。

Is there a simpler way to do this? 有没有更简单的方法可以做到这一点? I wish I understood how the diff works better so that my object gets rendered when I set the attribute tired to true for a given row. 我希望我能理解diff如何更好地工作,以便当我将给定行的属性疲倦设置为true时,可以渲染对象。 It feels like I'm just thrashing everything. 感觉就像我在重击一切。

        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;

if you know the id you want to update and im assuming you have an array of objects then you can do something like 如果您知道要更新的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);

Now you want to set the state of your data 现在您要设置数据状态

this.setState({data:arr});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM