[英]Infinite loop when using useLazyQuery in React + Apollo/GraphQL?
My code so far looks something like this:到目前为止,我的代码看起来像这样:
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 {...}
What I'm essentially doing is finding an object with the specified ID
first, and then querying for its subObjects.我实际上在做的是首先找到具有指定
ID
的 object,然后查询其子对象。 I want to first find the objectWithID
variable before querying, and then based on one of its parameters, conditionally use its value, hence I think useLazyQuery
helps to achieve this.我想在查询之前先找到
objectWithID
变量,然后根据它的一个参数,有条件地使用它的值,因此我认为useLazyQuery
有助于实现这一点。 However, this causes an infinite loop: for some reason it's being called an infinite number of times, crashing my webpage.但是,这会导致无限循环:由于某种原因,它被无数次调用,导致我的网页崩溃。 Am I using
useLazyQuery
incorrectly?我是否错误地使用
useLazyQuery
? How could I prevent this infinite loop?我怎样才能防止这个无限循环?
In this case, you're executing the query inside the render method, meaning it'll just keep firing.在这种情况下,您在 render 方法中执行查询,这意味着它会一直触发。 Instead, consider using a
useEffect
hook:相反,请考虑使用
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</>
);
Note that I also threw in a useMemo
hook to memoize the objectWithID
value so it only changes when props.data
or ID
changes.请注意,我还添加了一个
useMemo
挂钩来objectWithID
值,因此它仅在props.data
或ID
更改时才会更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.