简体   繁体   中英

How to change state in React

I am having a simple state, which defines a price of the coffee for employees, if the radio button is checked.

const [coffee, setCoffee] = useState(0);    
const [checkedCoffee, setCheckedCoffee] = useState(true);

This is how I am setting up the new state:

 useEffect(() => {
        if (checkedCoffee) {
            setCoffee(employees * 40);
        } else {
            setCoffee(0);
        }
}, [coffee])

But I want to have another option, which will reduce the coffee price 50% and this is how I am trying to handle it:

 const handleDivision = () => {
        setCoffee(coffee / 2);
    };

And then just calling handleDivision in onClick button.

 <button onClick={handleDivision}>division button</button>

The result is just refreshing the price divided by 2 - so something is happening, but it never actually set up the 50% less price.

Where does my code conflicts?

You can see in the documentation for useEffect that it states:

The function passed to useEffect will run after the render is committed to the screen. Think of effects as an escape hatch from React's purely functional world into the imperative world.

Based on the statement from the documentation, it looks like your useEffect function will execute again after you've clicked your button and refresh the value based on the useEffect function eg

 if (checkedCoffee) {
     setCoffee(employees * 40);
 } else {
     setCoffee(0);
 }

In order to fix this you can remove the useEffect call in component and execute the above code inplace or as a seperate function call.

Try this :

<button 
     onClick={()=>{
          handleDivision()
     }}>
              division button
</button>`

Instead of :

<button onClick={handleDivision}>division button</button>

Check out this sandbox:

https://codesandbox.io/s/optimistic-cache-4c9ud?file=/src/App.js

Try this:

 const handleDivision = () => {
    setCoffee(prevCoffePrice => prevCoffePrice / 2);
};

Add checkedCoffee to useEffect dependency list.

useEffect(() => {
  if (checkedCoffee) {
    setCoffee(employees * 40);
  } else {
    setCoffee(0);
  }
}, [checkedCoffee]);

And then:

...

const handleDivision = () => {
  setCoffee(coffee / 2);
};

return <button onClick={handleDivision}>division button</button>;
...

Look at the example here → https://codesandbox.io/s/brave-grothendieck-floly?file=/src/App.js

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