防止this.state与setState一起使用 [英] Prevent this.state to be used with setState

查看:163
本文介绍了防止this.state与setState一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考声明:


setState()并不总是立即更新组件。它可以批量推迟更新或推迟更新。这使得在调用setState()之后立即读取this.state是一个潜在的陷阱。相反,使用componentDidUpdate或setState回调(setState(更新程序,回调)),其中任何一个都保证在应用更新后触发。如果你需要根据以前的状态设置状态,请阅读下面的updater参数。

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.

所以它被认为是一个错误反应使用 this.state 值和 setState 因为 setState 是异步的,可能导致用错误的值更新状态(演示):

So it is considered a mistake in React to use this.state values together with setState because setState is asynchronous and may result in updating the state with wrong values (a demo):

// destructured
const { state, setState } = this;
setState({ foo: state.foo });

// destructured
const { foo } = this.state;
setState({ foo });

// undestructured
this.setState({ foo: this.state.foo });

虽然这是更新状态的正确方法(演示):

While this would be proper way to update the state (a demo):

// destructured
this.setState(({ foo }) => ({ foo }));

// undestructured
this.setState(state => ({ foo: state.foo }));

是否有ESLint规则或其他方法来防止部分或全部这些情况 this.state 可以被误用吗?

Is there ESLint rule or other way to prevent some or all of these cases where this.state can be misused?

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

I assume it may be hard but possible to solve this case with static analysis.

推荐答案

eslint-plugin-react 将使用 react / no-access-state-in-setstate 规则


此规则应阻止在setState调用中使用this.state。当批量调用两个状态调用并因此引用旧状态而不是当前状态时,this.state的这种使用可能导致错误。

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.

这篇关于防止this.state与setState一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆