在过去的几天里,我一直在学习React,看一些关于你可以编写不同元素的不同方法的教程和解释.然而,有一个我最好奇的 - setState更新/覆盖state组件属性的功能.
例如,假设我有一个具有以下内容的类:
class Photos extends React.Component {
constructor() {
super()
state = {
pictures: []
}
}
componentDidMount() {
// This is where the fetch and setState will occur (see below)
}
render() {
return {
<div className="container">
{this.state.pictures}
</div>
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个例子看到我从API获取图像.
鉴于我已经为此函数执行了我的获取,映射和返回 - 然后我将pictures: []使用API调用中获得的结果更新状态数组.
我的问题源于我见过的关于如何更新/覆盖图片状态属性的不同方法.
我看过它有两种不同的方式:
1) 这似乎是一种非常简单易读的方法
this.setState({pictures: pics})
2) 这更复杂,但我认为它被描述为更安全的方法
this.setState(prevState => ({
pictures: prevState.pictures.concat(pics)
}))
Run Code Online (Sandbox Code Playgroud)
有人可以解释使用其中任何一个的优点吗?我想在未来与代码保持一致,处理道具和状态等,所以最通用的方法当然是首选.