gpt4 book ai didi

javascript - Concat vs 插入在 React 最佳实践中添加新数组

转载 作者:数据小太阳 更新时间:2023-10-29 06:00:20 26 4
gpt4 key购买 nike

许多人提倡不可变性,因为他们将 redux 与 react 一起使用,但我仍然看到人们使用 push 而不是 concat。

以这段代码为例:

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
})
})
}

在这种情况下,这重要吗?上面的推送有什么问题?

最佳答案

在 React 中使用不可变性,不仅仅是因为 redux。 React 组件的状态不应该直接改变。根据docs :

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

此外,immutability也有助于和解。如果 Prop 是不可变的,您可以进行浅层相等性检查以查看它是否已更改,并相应地进行渲染。

在您的代码中,使用 Object#assignupdatedList 克隆到一个新数组。现在你可以 Array#push 到数组,而不改变原来的数组。使用 Array#concat 更短,更易读:

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

关于javascript - Concat vs 插入在 React 最佳实践中添加新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41616376/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com