React的state和setState()方法

1.不要直接修改 State

eg:例如,此代码不会重新渲染组件:

// Wrong
this.state.comment = 'Hello';

而是应该使用 setState():

// Correct
this.setState({comment: 'Hello'});

构造函数是唯一可以给 this.state 赋值的地方

2.State 的更新可能是异步的

出于性能考虑,React 可能会把多个 setState() 调用合并成一个调用。

因为 this.props 和 this.state 可能会异步更新,所以你不要依赖他们的值来更新下一个状态。

例如,此代码可能会无法更新计数器:

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

要解决这个问题,可以让 setState() 接收一个函数而不是一个对象。这个函数用上一个 state 作为第一个参数,将此次更新被应用时的 props 做为第二个参数:

// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

想要获取修改后的state,需要在state的回调函数获取

this.setState((state, props) => ({
  counter: state.counter + props.increment
}), () => {

    //在这里可以获取修改后的state
    
};
发布了19 篇原创文章 · 获赞 0 · 访问量 142

猜你喜欢

转载自blog.csdn.net/DxCaesar/article/details/104276608
今日推荐