如何在 React 中改变状态

How to change state in React

我有一个简单的状态,如果选中单选按钮,它会为员工定义咖啡的价格。

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

这就是我设置新状态的方式:

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

但我想有另一种选择,它将咖啡价格降低 50%,这就是我尝试处理它的方式:

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

然后只需在 onClick 按钮中调用 handleDivision

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

结果只是刷新了除以 2 的价格 - 所以发生了一些事情,但实际上并没有设置 50% 的价格。

我的代码哪里有冲突?

试试这个:

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

而不是:

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

查看此沙箱:

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

您可以在 useEffect 的文档中看到它指出:

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.

根据文档中的说明,您的 useEffect 函数看起来会在您单击按钮并根据 useEffect 函数刷新值后再次执行,例如

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

为了解决这个问题,您可以删除组件中的 useEffect 调用并就地执行上述代码或作为单独的函数调用执行。

试试这个:

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

checkedCoffee 添加到 useEffect 依赖项列表。

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

然后:

...

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

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

看这里的例子→https://codesandbox.io/s/brave-grothendieck-floly?file=/src/App.js