代码之家  ›  专栏  ›  技术社区  ›  Estus Flask

阻止此.state与setState一起使用

  •  3
  • Estus Flask  · 技术社区  · 7 年前

    The reference 国家:

    因此,这被认为是一个错误的反应使用 this.state setState 因为 设置状态 是异步的,可能会导致用错误的值更新状态(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 });
    

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

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

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

    2 回复  |  直到 7 年前
        1
  •  3
  •   skyboyer    7 年前

    eslint-plugin-react 我会和你一起检查的 react/no-access-state-in-setstate 规则

    此规则应防止在setState调用中使用This.state。当批调用两个状态调用时,使用this.state可能会导致错误,从而引用旧状态而不是当前状态。

        2
  •  3
  •   Bhojendra Rauniyar    7 年前

    如果您使用:

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

    state.foo (访问对象的属性)。为了避免这种情况,您可以定义如下:

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

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

    然后,ESLINT将警告您使用如下解构语法:

    const { foo } = this.state
    this.setState({foo})
    

    注:自 foo 是要更新的变量名,并且名称匹配,我们可以使用 {foo} {foo: foo}


    但是,我更喜欢使用 this.setState() 语法而不是对 this . 因为,在任何应用程序中,我们都使用 必要时。以及使用 const { ... } = this setState 而不是 this.setState . 像第三个开发者一样思考。


    从注释中,您希望一个接一个地更新状态,那么您应该使用如下回调:

    onClick = () => {
       this.setState({ foo: 'Bar' }, () => {
          this.setState({ foo: this.state.foo + '!' });
       });
    }
    

    现在,您可以看到 Hello Bar! 在你的演示中。

    如果您这样使用setState:

    onClick = () => {
       this.setState({ foo: 'Bar' })
       this.setState({ foo: this.state.foo + '!' });
       // obviously, better to use updater syntax though.
    }
    

    Hello Foo! 在你的演示中。

    文件中也有同样的规定。更新程序语法只是一个方便的方法,但结果与没有更新程序语法时完全相同。最重要的角色只是它的回调语法。使用回调语法,以便您可以在更新后立即访问更新的状态。


    了解更多关于解构语法的知识。你可以跟着 my another post 在那里,你可以找到详细的信息和一些链接,这将是很多人熟悉。