看了一个文章, 我发现react和胖箭头, 我都没弄明白
https://www.sitepoint.com/javascript-private-class-fields/

//老的写法
class App extends Component {
  constructor() {
    super();
    state = { count: 0 };
    // bind all methods
    this.incCount = this.incCount.bind(this);
  }
  incCount() {
    this.setState(ps => ({ count: ps.count + 1 }));
  }
  render() {
    return (
      <div>
        <p>{ this.state.count }</p>
        <button onClick={this.incCount}>add one</button>
      </div>
    );
  }
}

//新的写法
class App extends Component {
  state = { count: 0 }; //作者推荐直接赋值, 不用构造函数.
incCount = () => {
  this.setState(ps => ({ count: ps.count + 1 }));
};
render() {
  return (
    <div>
      <p>{ this.state.count }</p>
      <button onClick={this.incCount}>add one</button>
    </div>
  );

}
}
官方文档依旧硬核
  • https://zh-hans.reactjs.org/docs/state-and-lifecycle.html

  • 正确使用state要做三件事:

    • 不能直接修改state, 构造函数是唯一可以给this.state赋值的地方. (这里有问题了, 按照上面引用的话, 应该可以直接搞.) 正常应该setState.

    • state是异步的, 所以不能直接依赖, 但是可以给setstate一个函数作为参数.

      • 这个函数有两个参数, 第一个是前一个state, 第二个是props.
      // Correct
      this.setState((state, props) => ({
        counter: state.counter + props.increment
      }));
      
    • state更新会被合并.

  • react并没有问题, 因为函数在执行时才会确定this. 所以如果直接赋值到某个地方, 就会导致this缺失.

参考
  • 我的另一篇blog: 我的js一无所知this和bind