[英]Infinite loop when using useLazyQuery in React + Apollo/GraphQL?
到目前为止,我的代码看起来像这样:
const { ID } = useParams();
const [getObjects, {loading, data}] = useLazyQuery(GET_OBJECTS_BY_ID);
const objectWithID = props.data.find(datum => datum._id == ID);
if (objectWithID.conditional) {
getObjects({variables: {objectIds: objectWithID.subObjects}});
//Do a bunch of other stuff including a separate render
}
else {...}
我实际上在做的是首先找到具有指定ID
的 object,然后查询其子对象。 我想在查询之前先找到objectWithID
变量,然后根据它的一个参数,有条件地使用它的值,因此我认为useLazyQuery
有助于实现这一点。 但是,这会导致无限循环:由于某种原因,它被无数次调用,导致我的网页崩溃。 我是否错误地使用useLazyQuery
? 我怎样才能防止这个无限循环?
在这种情况下,您在 render 方法中执行查询,这意味着它会一直触发。 相反,请考虑使用useEffect
挂钩:
const { ID } = useParams();
const [getObjects, { loading, data }] = useLazyQuery(GET_OBJECTS_BY_ID);
const objectWithID = useMemo(() => {
return props.data.find((datum) => datum._id == ID);
}, [props.data, ID]);
useEffect(() => {
if (objectWithID.conditional) {
getObjects({ variables: { objectIds: objectWithID.subObjects } });
}
}, [getObjects, objectWithID]);
return objectWithID.conditional ? (
<>Render one thing</>
) : (
<>Render the other thing</>
);
请注意,我还添加了一个useMemo
挂钩来objectWithID
值,因此它仅在props.data
或ID
更改时才会更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.