参考文献指出:
setState() 并不总是立即更新组件。它可能会批量更新或推迟更新。这使得在调用 setState() 后立即读取 this.state 成为一个潜在的陷阱。相反,使用 componentDidUpdate 或 setState 回调 (setState(updater, callback)),这两者都保证在应用更新后触发。如果您需要根据之前的状态设置状态,请阅读下面的更新程序参数。
所以在 React 中使用this.state
值被认为是错误的,setState
因为它setState
是异步的,可能会导致用错误的值更新状态(演示):
// destructured
const { state, setState } = this;
setState({ foo: state.foo });
// destructured
const { foo } = this.state;
setState({ foo });
// undestructured
this.setState({ foo: this.state.foo });
虽然这将是更新状态的正确方法(演示):
// destructured
this.setState(({ foo }) => ({ foo }));
// undestructured
this.setState(state => ({ foo: state.foo }));
是否有 ESLint 规则或其他方法来防止这些this.state
可能被滥用的部分或全部情况?
我认为这可能很难,但可以通过静态分析解决这种情况。