简体   繁体   中英

ReactJS ES6 Arrow Function

    import React, { useState } from 'react';
    
    function Example() {
      // Declare a new state variable, which we'll call "count"
      const [count, setCount] = useState(0);
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={**() => setCount(count + 1)**}>
            Click me
          </button>
        </div>
      );
    }

Can someone explain to me the bolded block of code or convert it into ES5. I think I understand the arrow function but guess not. What I know about arrow function is... You use it like this,

const timesTwo = (a) => { return a*2 } or
const timesTwo = a => a*2 or
const timesTwo = a =>( a*2)

I don't understand this piece of code () => setCount(count + 1) I understand that count is going to increase as soon as user clicks but is it same as writing

function setCount(){
 count: count +1;
}

Thank You, I appreciate your time.

The function you have in the onClick event is equivalent to:

function() {
  return setCount(count + 1);
}

But you don't need to return the setCount value, so it's better to change it to

()=> { setCount(count + 1); }

Or just:

function() {
  setCount(count + 1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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