简体   繁体   English

求教:最大更新深度超出原因

[英]Seeking advice: Reason for maximum update depth exceed

I am new to React and GraphQL.我是 React 和 GraphQL 的新手。 Trying to update React state with GraphQL subscription feed but it generates the update depth error.尝试使用 GraphQL 订阅源更新 React 状态,但会生成更新深度错误。

Here is the simplified code:这是简化的代码:

import { Subscription } from 'react-apollo';
...

function Comp() {
  const [test, setTest] = useState([]);

  const Sub = function() {
    return (
      <Subscription subscription={someStatement}>
        {
          result => setTest(...test, result.data);
          return null;
        }
      </Subscription> 
    );
  };

  const Draw = function() {
    return ( 
      <div> { test.map(x => <p>{x}</p>) } </div> 
    );
  };

  return (
    <div>
      <Sub />
      <Draw />
    <div/>
  );
};
export default Comp;

Regular query works fine in the app and the Subscription tag returns usable results, so I believe the problem is on the React side.常规查询在应用程序中运行良好,订阅标签返回可用结果,所以我相信问题出在 React 端。

I assume the displayed code contains the source of error because commenting out the function "Sub" stops the depth error.我假设显示的代码包含错误源,因为注释掉函数“Sub”会停止深度错误。

You see what happens is when this part renders你会看到当这部分渲染时会发生什么

    <Subscription subscription={someStatement}>
        {
          result => setTest(...test, result.data);
          return null;
        }
      </Subscription> 

setTest() is called and state is set which causes a re-render, that re-render cause the above block to re-render and setTest() is called again and the loop goes on. setTest()并设置 state 导致重新渲染,重新渲染导致上述块re-render并再次调用setTest()并继续循环。

Try to fetch and setTest() in your useEffect() Hook so it does not gets stuck in that re-render loop.尝试在useEffect()钩子中获取和setTest()以便它不会卡在重新渲染循环中。

useEffect like使用效果像

  useEffect(() => {
           //idk where result obj are you getting from but it is supposed to be 
           //like this
      setTest(...test, result.data);
  }, [test] )

Component Like组件喜欢

 <Subscription subscription={someStatement} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM