简体   繁体   中英

Concat vs push adding new array in react best practice

Many folks promote immutability because they use redux altogether with react, but I'm still seeing people using push instead of concat.

Take this code for example:

submitComment() {
  console.log('submitComment: '+JSON.stringify(this.state.comment))

  APIManager.post('/api/comment', this.state.comment, (err, response) => {
    if (err){
      alert(err)
      return
    }

    console.log(JSON.stringify(response))
    let updateList = Object.assign([], this.state.list)
    updatedList.push(response.result)
    this.setState({
      list: updatedList
    })
  })
}

in this case does it matter at all? What's the issue with push above?

Immutability is used in react and not only because of redux. React component's state should not be mutated directly. According to the docs :

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

In addition, immutability also helps in reconciliation. If props are immutable, you can make a shallow equality check to see if it's changed or not, and render accordingly.

In your code updatedList is cloned to a new array using Object#assign . Now you can Array#push to the array, without changing the original one. Using Array#concat is a bit shorter, and more readable:

const updatedList = this.state.list.concat(response.result);

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