在仔细研究之后,我想我明白组件的属性不能由组件本身更新,尽管可以由父组件更改。
但是我在 React 文档中找到了这一节:
React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.
所以我试图用我理解的方式来解释这段摘录的内容。如果 props 被更新,那么更新必须来自父组件。如果更新来自父组件,为什么它可能是异步的?
最佳答案
请查看zloctb给出的答案here
// assuming this.state.count === 0
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
this.setState({count: this.state.count + 1});
// this.state.count === 1, not 3
Solution
this.setState((prevState, props) => ({
count: prevState.count + props.increment
}));
关于javascript - React 组件的 props 是如何异步更新的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51354162/