我正在尝试更新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 });
,但这会导致无限循环。我在这里错了吗?
因为您在效果内有setColoredBar(opacityBar);
,并且coloredBar
是运行该效果的触发器之一,所以每次您完成效果时,都需要再次启动它。只需将检查器添加到setColoredBar(opacityBar);
您不应该将colorBar添加为useEffect的依赖项,因为您要在其中设置相同的状态。这样做将导致无限循环。