简体   繁体   中英

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. 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. 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

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});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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