Concat vs push adds new array to better cutting-edge response

Many people contribute to immutability because they generally use reduction, but I still see that people use 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 is the problem with clicking above?

+4
source share
1 answer

Immutability is used in the reaction and not only because of contraction. The state of the reactive component should not be mutated directly. According to the docs :

Never mutate this.state directly, since calling setState () can subsequently replace the mutation you made. Relate to this. As if it's immutable.

, . , , , , .

updatedList Object#assign. Array # , . Array # concat :

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

Source: https://habr.com/ru/post/1666618/


All Articles