如何从if语句正确设置状态

问题描述 投票:0回答:2

我正在尝试更新useEffect挂钩中的状态,但出现了问题。在钩子内部,我有if语句,其中要在opacityBar变量中设置数据,而在if之外,我需要使用该变量更新状态,但它不起作用。这是我的代码:

React.useEffect(() => {
   let opacityBar;
   if(filteredData.length > 0) {
      const inc = (name) => filteredData.find((f) => f.name === name) !== undefined;

   opacityBar = coloredBar?.data?.map((bar: any) => ({ ...bar, opacity: inc(bar.name) ? 1 : 0.333 }));
   } else {
      opacityBar = coloredBar?.data?.map((bar: any) => ({ ...bar, opacity: 1 }));
   }

   setColoredBar(opacityBar);
}, [filteredData, coloredBar]);

我也试图像这样设置状态setColoredBar({ ...coloredBar, opacityBar });,但这会导致无限循环。我在这里错了吗?

reactjs react-hooks
2个回答
0
投票

因为您在效果内有setColoredBar(opacityBar);,并且coloredBar是运行该效果的触发器之一,所以每次您完成效果时,都需要再次启动它。只需将检查器添加到setColoredBar(opacityBar);


0
投票

您不应该将colorBar添加为useEffect的依赖项,因为您要在其中设置相同的状态。这样做将导致无限循环。

© www.soinside.com 2019 - 2024. All rights reserved.