setState 在 useEffect 之后不更新状态

setState not updating state after useEffect

我正在制作一个购物车应用程序,我有一个循环遍历所有价格并获取购物车总价的变量。我试图让总金额通过 setTotals 更新总计状态,但是当总变量本身随着从购物车中删除项目而更新时,调用 setTotals(total) 不会更新状态。它保持渲染时的初始状态(购物车中所有价格的总价)。

我的州声明:

const [totals, setTotals] = useState()

从价格数组中获取总数:

 var total = 0
    for (var i = 0; i < prices.length; i++) {
        total += prices[i];
    }

在 useEffect 中调用 setTotals:

   useEffect(() => {
    setTotals(total) <-- From the loop above
    setCartCopy([...deepCartCopy])
}, [totals])

有人可以帮忙吗?

  const [finalTotal, setFinalTotal] = useState(0);

  let total = 0;
  for (let i = 0; i < prices.length; i++) {
    total += prices[i];
  }

  useEffect(() => {
    setFinalTotal(total);
  }, [total, setFinalTotal]);

https://codesandbox.io/s/Whosebughelp-i70fd?file=/src/App.js

我认为你的卡片代码方法不是很好。

这里你总是有两次相同的信息:你在 total 中得到总数,然后你在 totals 中设置相同的结果。您可以通过仅保留两个变量之一来简化。

此外,您的代码无法正常工作,因为永远不会执行 useEffect:正如您将 totals 作为依赖项一样,但它永远不会改变。即使您在其他地方更改 totals,您也会有一个无限循环,因为在 useEffect 中,根据 totals 的更改,它会更改它的值,这将执行更改 totals 的 useEffect等等,无限循环。

我认为你的循环也应该在没有依赖关系的 useEffect 中,因为它只会在第一次渲染时执行。

我会做那样的事情,也许代码可以改进:

  const [prices, setPrices] = useState([1, 3, 6, 39, 5]);
  const [total, setTotal] = useState(0);

  useEffect(() => {
    // Sets total with already present products in the card
    // This useEffect is called only at the first render
    prices.forEach((price) => {
      setTotal((total) => total + price);
    });
  }, []);

  useEffect(() => {
    setTotal((total) => total + prices[prices.length - 1]);
     // Called when prices values changes, like if you're adding a product to your card
     // It keeps your total updated
  }, [prices]);

  const addPrice = () => {
    // Simulate a new product in your card
    setPrices((prices) => [...prices, Math.floor(Math.random() * 10)]);
  };

  return (
    <div className="App">
      <p>total: {total}</p>
      <button onClick={() => addPrice()}>add price</button>
    </div>
  );

我希望我的回答很清楚哈哈