state的理解

针对state要明确三件事:
1.不要直接修改state

// 错的
this.state.name = 'alice';

应该使用setState()

// 正确
this.setState({
	name: 'alice'
});

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

  constructor(props) {
    super(props);
    this.state = {
		name: 'alice'
	};
  }

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

setState()函数是异步的,因此,更新数据时可能会异步更新。所以不要依赖要更新的值去更新下一个状态。

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

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

3.state的更新会被合并

当调用setState()的时候,React会把提供的对象合并到当前的state。

// Correct
  constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: []
    };
  }

分开更新

  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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章