简体   繁体   English

React中这两个ES6箭头功能有什么区别?

[英]What is the difference in these two ES6 arrow functions in React?

If I click a button, it calls handleClick which increases the value of the button by 1 from 0. I have made the handleClick code work in two different scenarios. 如果单击按钮,它将调用handleClick ,该按钮会将按钮的值从0增加1。我已经使handleClick代码在两种不同的情况下工作。 I understand the first, I don't seem to grasp the second one. 我了解第一个,但我似乎不太了解第二个。

I wrote this one. 我写了这个。 And it works. 而且有效。

handleClick = () => {
    this.setState({count: this.state.count + 1})
  }

The tutorial shows this one and it works too. 本教程显示了这一点,它也可以工作。

handleClick = () => {
    this.setState(({count}) => ({
      count: count + 1
    }))
  }

If I change the code to this, this works too. 如果我将代码更改为此,也可以。

handleClick = () => {
    this.setState(() => ({
      count: this.state.count + 1
    }))
  }

What is the advantage of using the second body of code when it does the same thing but is more complex than the first one? 当第二个代码体执行相同的操作但比第一个代码体更复杂时,使用它的好处是什么?

I understand I am returning an object literal which is basically what I wrote instead of generating it in the first code body. 我知道我要返回的对象字面量基本上是我写的,而不是在第一个代码主体中生成它。 But why am I passing {count} as a parameter when I can keep the parameter empty and just use this.state.count in the body? 但是,当我可以将参数保留为空并仅在主体中使用this.state.countthis.state.count传递{count}作为参数呢?

In React, this.setState() queues the change. 在React中, this.setState()将更改排队。 It is not guaranteed to happen right away. 不能保证立即发生。 So the value of this.state.count may have changed by the time setState actually makes the change. 因此,在setState实际进行更改之前, this.state.count的值可能已更改。

In the second version, you're passing a function to this.setState() . 在第二个版本中,您正在将一个函数传递给this.setState() When React is ready to change the state, that function is called, with the current state as an argument. 当React准备好更改状态时,将调用该函数,并以当前状态作为参数。 This lets you ensure that the state is incremented correctly. 这样可以确保状态正确递增。

The React documentation goes into more detail. React文档更加详细。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM