【发布时间】:2018-10-08 09:17:00
【问题描述】:
The reference 状态:
setState() 并不总是立即更新组件。它可能会批量更新或将更新推迟到以后。这使得在调用 setState() 之后立即读取 this.state 是一个潜在的陷阱。相反,使用 componentDidUpdate 或 setState 回调 (setState(updater, callback)),它们都保证在应用更新后触发。如果您需要根据之前的状态设置状态,请阅读下面的 updater 参数。
因此在 React 中将 this.state 值与 setState 一起使用被认为是错误的,因为 setState 是异步的,并且可能导致使用错误的值更新状态(demo):
// destructured
const { state, setState } = this;
setState({ foo: state.foo });
// destructured
const { foo } = this.state;
setState({ foo });
// undestructured
this.setState({ foo: this.state.foo });
虽然这是更新状态的正确方法(demo):
// destructured
this.setState(({ foo }) => ({ foo }));
// undestructured
this.setState(state => ({ foo: state.foo }));
是否有 ESLint 规则或其他方法来防止 this.state 可能被滥用的部分或全部情况?
我认为用静态分析解决这个问题可能很困难,但可以解决。
【问题讨论】:
标签: javascript reactjs eslint static-analysis