问题描述
到目前为止,我的代码如下所示:
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
的对象,然后查询其子对象。我想在查询之前先找到 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
更改时才会更改。