Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

javascript - Error while updating redux state using immutability-helper

I'm trying to set one exact value, stored in array which is stored in my state object, all in redux.

const initialState = {
    orderedItems: [
    {item:"1Reco",price:"12",amount:1},
    {item:"2Reco",price:"12",amount:1},
    ],
    fullPrice: 0,
    windowWidth: 1418,
    language: "en"
};

Let's say 2Reco amount to 2. I have been trying to use update and $set like that:

let newamount = state.orderedItems[i].amount+1;
return update(state, { 
    orderedItems: { 
        [i]: {
            amount: {$set:newamount}
      }
    },fullPrice: newPrice
  });

But when this update is firing,im getting "Error: update(): You provided an invalid spec to update()." back, and I don't know why. I have seen simillar solutions here on stack earlier, and they don't seem to work for me. When console logging, newamount shows a number 2, so exactly what I want to set in that place. What is the problem?

question from:https://stackoverflow.com/questions/65829446/error-while-updating-redux-state-using-immutability-helper

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are mutating the state directly. In a general scenario in Redux you must ... operator. Something like this:

For

orderedItems: [
  {item:"1Reco",price:"12",amount:1},
  {item:"2Reco",price:"12",amount:1},
],

Try

const updatedOrderedItems = orderedItems.map(obj=>{
                if(obj.item==="2Reco"){
                    obj.amount=obj.amount+1;
                    return obj; 
                }
                return obj;
});

Now your updatedOrderedItems contains the updated array of object containing the amount 2 for second object.

Then you can update global state in redux from your reducer function as follows:

return{
  ...state,
    orderedItems: updatedOrderedItems 
    fullPrice: 0,
    windowWidth: 1418,
    language: "en"
   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...