警告:在渲染不同的 Y 组件时无法更新组件 X 要在 Y 中找到错误的 setState() 调用,

S. *_*. N 7 javascript reactjs redux react-redux

我有一个带有react-redux的Cart组件,还有一个showProducts组件,它从useEffect内的API(使用await-async)获取产品,然后我使用useState来设置一些状态并使用dispatch来更新redux状态也是如此。我不断收到此警告:

Warning: Cannot update a component (`Cart`) while rendering a different component (`ShowProducts`). To locate the bad setState() call inside `ShowProducts`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
ShowProducts@http://localhost:3000/static/js/main.chunk.js:3099:73
Run Code Online (Sandbox Code Playgroud)

我有一个商店页面,在我的商店页面中有:

 <Grid item xs container >
    <ShowProducts />
 </Grid>
 <Grid item xs container direction="column">
    <Cart />
 </Grid>
Run Code Online (Sandbox Code Playgroud)

在我的展示产品中:

useEffect(async () => {
    await getData();
  }, []);
  .
  dispatch(setShippingCosts);
  dispatch(setCompanyNam);
  .
  .
  .
  async function getData() {
    fetch(
      `url`
    )
      .then((res) => res.json())
      .then((data) => {
       .
       .
       .
        setProducts(...);
        setShippingCost(...);
       .

      })
      .catch((error) => {
        setError(error);
      });
  }
Run Code Online (Sandbox Code Playgroud)

在我的购物车中,我使用的是来自展示产品组件的运费。我不知道如何解决这个警告,我一直在寻找,但还没有找到解决方案。这个警告有多严重,我不确定为什么会收到它。

完整警告: 在此输入图像描述

Zoh*_*rut 17

问题是当一个组件在另一个组件中排队更新,而第一个组件正在渲染时。\n(错误:太难修复“无法从不同组件的函数体内部更新组件。”

\n

问题

\n

在呈现 ShowProducts 时,它还会调度一个操作,导致在购物车中对更新进行排队。

\n

使固定

\n

将调度移至 useEffect 内。

\n

解释

\n

通过使用这个 Hook,您可以告诉 React 您的组件需要在渲染后执行某些操作。React 会记住您传递的函数(我们\xe2\x80\x99 将其称为 \xe2\x80\x9ceffect\xe2\x80\x9d),并在执行 DOM 更新后调用它。\n useEffect 做什么?

\n

下面是沙盒笔演示bug及修复。\n(打开右下角控制台可以看到警告,可以注释掉渲染中的dispatch,看到警告消失)

\n

请注意,您正在使用 useEffect 异步,并且它应该仅是同步的。在这里阅读

\n


gan*_*alf 6

我遇到了同样的问题,而且问题的根源有点不同,它导致了同样的错误。

我试图在supdater的回调主体中更新父组件的状态(通过回调道具) 。像这样:useStatesetState

...
const [state, setState] = useState();

useState((prev) => {
  const newState = someOperationToGenerateNewStateFromTheOldOne(prev);
  updateStateOfParentComponent();//this call caused the issue because as the error says causes update of parent component during the state change(render) of this component
  return newState;
})
Run Code Online (Sandbox Code Playgroud)

作为修复,您可以useEffect像这样使用:

...
const [state, setState] = useState();
useEffect(() => {
   updateStateOfParentComponent();
}, [state])

useState((prev) => {
  return someOperationToGenerateNewStateFromTheOldOne(prev);
})
Run Code Online (Sandbox Code Playgroud)