简体   繁体   English

Concat vs推动添加新阵列的最佳实践

[英]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. 许多人提倡不变性,因为他们完全使用redux和反应,但我仍然看到人们使用push而不是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. 不应直接改变React组件的状态。 According to the docs : 根据文件

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. 永远不要直接改变this.state,因为之后调用setState()可能会替换你所做的突变。 Treat this.state as if it were immutable. 把this.state看作是不可变的。

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. 如果props是不可变的,您可以进行浅等式检查以查看它是否已更改,并相应地进行渲染。

In your code updatedList is cloned to a new array using Object#assign . 在您的代码中,使用Object#assign updatedList克隆到新数组。 Now you can Array#push to the array, without changing the original one. 现在您可以将Array#推送到数组,而无需更改原始数组。 Using Array#concat is a bit shorter, and more readable: 使用Array#concat更短,更易读:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM