正如我在评论中提到的,您需要查看文档本身以了解有关 how setState works 的更多信息。
此外,我想说明我们为什么需要它?
在反应状态是不可变的,即。说你不能直接改变状态:
state = { current: 1 }
// ...and somewhere in your code
this.state.current = 2 // won't work
this.state.current = this.state.current + 1 // also, no luck
console.log(this.state.current) // 1
// the reason is immutable
因此,您需要在不改变状态的情况下更新状态。因此,react 让我们公开使用 setState。
setState 有两个参数:updater 和 callback。
更新程序可以接受状态和道具。这样您就可以根据状态和道具或您想要的其他方式更新状态检查其条件。
回调是在 setState 中提供的,因此您可能知道它的效果,就像现在的 current 一样。请参阅下面的示例:
this.setState((state, props) => { // previous state, previous props
// you may additionally check some condition
// or combine state and props
// like, state.current + props.value
return { current: state.current + 1 }
}, () => {
// ^^- callback
console.log(this.state.current)
})
顺便说一句,使用 setState 有一些不同的选项:
a) without updater and callback
eg. setState({current: 2})
b) with updater param only
eg. setState(()=>({current: 2}))
c) with updater and callback
eg. see preceding example of code
d) without updater but with callback
eg. setState({current: 2},()=>console.log(this.state.current))