简体   繁体   中英

I cannot update my array state in react?

This is my code, can't figure out why this doesn't udpate my react state?

state = {
    popUpMessages:[]
  }
  popUpMessage(id,name) {
    console.log("id ",id,"name ",name)
    const addUserObject = { id, name };
    const newArray = [...this.state.popUpMessages, addUserObject]
    console.log("newArray = ",newArray)
    this.setState({ popUpMessages: newArray });
  }

In this code popUpMessage gets invoked to update the state:

<li  onClick={() => this.popUpMessage(this.props.id,this.props.name)}>{this.props.name}</li>

but my state is not updating and when I try to log, the previous user object is removed? I want my state to be array of objects something like this:

[{id:1, name: kim bok joo},{id:2, name: ria atayde}]

The docs say that you should not depend on previous value of this.state when computing the new state.

But you do: const newArray = [...this.state.popUpMessages, addUserObject]

Try using a function that accepts the previous state and works with props, as shown in the docs.

As stated, not exactly recommended to do it this way. However, if you want to do it this way, this is all you have to do.

  popUpMessage(id,name) {
    const addUserObject = { id, name };
    const newArray = this.state.popUpMessages.concat([addUserObject])
    this.setState({ popUpMessages: newArray });
  }

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