正确使用state(状态)

关于 setState() 有三件事是你应该知道的。

一、不要直接修改 state(状态)

例如,这样将不会重新渲染一个组件:

// 错误
this.state.comment = 'Hello';

setState() 代替:

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

唯一可以分配 this.state 的地方是构造函数。

二、state(状态) 更新可能是异步的

React 为了优化性能,有可能会将多个 setState() 调用合并为一次更新。

因为 this.propsthis.state 可能是异步更新的,你不能依赖他们的值计算下一个state(状态)。

例如, 以下代码可能导致 counter(计数器)更新失败:

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

要解决这个问题,应该使用第 2 种 setState() 的格式,它接收一个函数,而不是一个对象。该函数接收前一个状态值作为第 1 个参数, 并将更新后的值作为第 2个参数:

要弥补这个问题,使用另一种 setState() 的形式,它接受一个函数而不是一个对象。这个函数将接收前一个状态作为第一个参数,应用更新时的 props 作为第二个参数:

// 正确
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

我们在上面使用了一个箭头函数,但是也可以使用一个常规的函数:

// 正确
this.setState(function(prevState, props) {
  return {
    counter: prevState.counter + props.increment
  };
});

三、state(状态)更新会被合并

当你调用 setState(), React 将合并你提供的对象到当前的状态中。

例如,你的状态可能包含几个独立的变量:

  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 的值。

猜你喜欢

转载自blog.csdn.net/zSY_snake/article/details/80860167