gpt4 book ai didi

javascript - 防止 this.state 与 setState 一起使用

转载 作者:数据小太阳 更新时间:2023-10-29 05:20:47 25 4
gpt4 key购买 nike

The reference状态:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

因此在 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 可能被滥用的部分或所有情况?

我认为用静态分析解决这个问题可能很难,但有可能。

最佳答案

eslint-plugin-react将使用 react/no-access-state-in-setstate 进行此项检查规则

This rule should prevent usage of this.state inside setState calls. Such usage of this.state might result in errors when two state calls are called in batch and thus referencing old state and not the current state.

关于javascript - 防止 this.state 与 setState 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52699006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com