[英]Seeking advice: Reason for maximum update depth exceed
我是 React 和 GraphQL 的新手。 尝试使用 GraphQL 订阅源更新 React 状态,但会生成更新深度错误。
这是简化的代码:
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;
常规查询在应用程序中运行良好,订阅标签返回可用结果,所以我相信问题出在 React 端。
我假设显示的代码包含错误源,因为注释掉函数“Sub”会停止深度错误。
你会看到当这部分渲染时会发生什么
<Subscription subscription={someStatement}>
{
result => setTest(...test, result.data);
return null;
}
</Subscription>
setTest()
并设置 state 导致重新渲染,重新渲染导致上述块re-render
并再次调用setTest()
并继续循环。
尝试在useEffect()
钩子中获取和setTest()
以便它不会卡在重新渲染循环中。
使用效果像
useEffect(() => {
//idk where result obj are you getting from but it is supposed to be
//like this
setTest(...test, result.data);
}, [test] )
组件喜欢
<Subscription subscription={someStatement} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.