简体   繁体   中英

how to push an item into an array if it is inside a javascript object [state.lastValue.push is not a function]

I'm updating some values as a javascript object inside my reducer in reactjs like below.

this is the object before the update

state = {
  result:1,
  lastval: []
}

and this is how I'm going to update it,

state = {
      ...state,
      result:state.result + 400,
      lastval: result.lastval.push(20)
    }

so this gives me an error of state.lastValue.push is not a function . but if I do it like below it is fine,

state = {
          ...state,
          result:state.result + 400,
        };
        state.lastval.push(20);

this is fine. what is the reason.

Update your state like

state = {
  ...state,
  result:state.result + 400,
  lastval: [...state.lastval, 20]
}

lastval: [...state.lastval, 20] will destructure all the contents inside the state.lastval array and add 20 to it and wrap it in an array again.

For more info on what [...state.lastval] does read What is the meaning of this syntax "{...x}" in Reactjs

Reason is, when you write:

state = {
   ...state,
   result:state.result + 400,
   lastval: result.lastval.push(20)
}

Final status of state will be:

state = {
   ...state,
   result:  some value
   lastval: 20
}

Means state.lasteval will become a number , it will not be an array , because a.push(1) will not return the final array , it will return the item pushed into array .

Write it like this to update the state:

state = {
   ...state,
   result: state.result + 400,
   lastval: [...state.lastval, 20]
}

Check this snippet:

 let a = [1,2]; let b = []; b = a.push(3); console.log('a', a); console.log('b', b); 

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