首页 > 解决方案 > React useState 导致 if-else 无法正常工作

问题描述

所以我试图在条件语句中使用useState钩子(React JS)设置一个值。if-else

我需要检查数组addOnName中是否有(作为参数传递),addOnContainer如果有,我需要将addOnPrice(也作为参数传递)减去totalprice使用setTotalPriceuseState钩子)。

如果addOnContainer不包括addOnName,我必须将 添加addOnPricetotalprice

该代码工作正常,因为它在 chrome 控制台中为我提供了正确的输出。但是当我尝试使用useState钩子设置总价时,只有 if 块运行,并且else无论条件如何,都不会运行。

我曾尝试将useState移出,if-else但没有运气。

我在这里做错了什么?请注意,此功能设置为在单击复选框时执行。

const [totalPrice, setTotalPrice] = useState(200)

function selectAddOn(addOnName, addOnPrice) {
  let temp = totalPrice

  if (!addOnContainer.includes(addOnName)) {
    temp = totalPrice + addOnPrice

    setTotalPrice(temp)
  } else {
    //never reaches even if the condition is false when useState is used.

    temp = totalPrice - addOnPrice

    setTotalPrice(temp)
  }
}

标签: javascriptreactjsreact-hooks

解决方案


在每次重新渲染时,let addOnContainer = [];都会重置为空数组。

您可以使用 auseRef来避免它:

const {useState, useRef} = React

function App() {

  const [totalPrice, setTotalPrice] = useState(200);
  const addOnContainer = useRef([]);
  // let addOnContainer = []; // This was the ISSUE

  function addToTotalPrice (addOnName, addOnPrice) {

    let temp = totalPrice;
    if(!addOnContainer.current.includes(addOnName)){
      addOnContainer.current.push(addOnName);
      temp = totalPrice + addOnPrice;
      setTotalPrice(temp)
    } else {
      temp = totalPrice - addOnPrice;
      setTotalPrice(temp);
    }
  }

  return (
    <button onClick={()=>addToTotalPrice('cheese',30)}>Click, totalPrice: {totalPrice}</button>
  );
}

ReactDOM.render(<App />, document.body)
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>


推荐阅读