在React+Apollo/GraphQL中使用useLazyQuery时的无限循环



到目前为止,我的代码看起来像这样:

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.dataID更改时更改。

最新更新