简体   繁体   中英

React hook to initial state - React native

i am currently working Hooks in react and have the following question, this simple code increments each time the button is pressed. i have create a condition that logs "finished" when the count is up to 2. However i am having trouble to put the count back to 0.

thank you very much in advance

here is my code:

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  if(count =='2'){
    console.log('finished')
    //count = 0
  }
  return (
    <div>
      <p>clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click here
      </button>
    </div>
  );
}

you need to use setCount method to set it back to 0

import React, { useState } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  if(count === 2){
    console.log('finished')
    setCount(0);
  }
  return (
    <div>
      <p>clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click here
      </button>
    </div>
  );
}

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