之前用 State 的时候还不熟,然后根据从返过来的 state 里面的数据来渲染。但是有时候拿不到这个数据,因为
State 的更新可能是异步的
例如
// Wrong
this.setState({
counter: this.state.counter + this.props.increment,
});
以前都是加个if(state.value???)来判断
今天又重新读了下 React 官方的文档
要解决这个问题,可以让 setState() 接收一个函数而不是一个对象。这个函数用上一个 state 作为第一个参数,将此次更新被应用时的 props 做为第二个参数:
// Correct
this.setState((state, props) => ({
counter: state.counter + props.increment
}));
写个箭头函数就 ok 了
并且还有一点要注意
当你调用 setState() 的时候,React 会把你提供的对象合并到当前的 state。
例如,你的 state 包含几个独立的变量:
constructor(props) {
super(props);
this.state = {
posts: [],
comments: [[
}
}
然后你可以分别调用 setState() 来单独地更新它们:
componentDidMount() {
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
}
这里的合并是浅合并,所以 this.setState({comments}) 完整保留了 this.state.posts, 但是完全替换了 this.state.comments。