useLazyQuery - 重新渲染问题
useLazyQuery - Re-Rendering Issue
要求:
我想在 useEffect 中第一次自动调用查询,然后在函数中手动调用。
Issue: Invarient Violation: Too many re-renders.
const [getComment, { loading, data }] = useLazyQuery(getCommentsQuery);
useEffect(() => {
getComment({
variables: {
input: {
id: "5e5cb512e90bd40017385305",
},
},
});
}, []);
if (data && data.getPost) {
var allNewComments = data.getPost.comments;
setAllComments(allNewComments); // re-renders
}
setState
导致了这个问题,我假设。
'Body parts' 的功能组件对于每个更改都是 运行,需要条件(或 useEffect
挂钩)来阻止意外行为。
只是不要将 useState
用于 allComments
?您可以使用 f.e.
const allNewComments = (data && data.getPost) ? data.getPost.comments : [];
...如果你想遍历 allNewComments
如果您仍然想使用 useState
(与 useLazyQuery
组合)...在 onCompleted
option/handler 中使用它,例如:
const [getComment, { loading, data }] = useLazyQuery(getCommentsQuery, {
variables: {
input: {
id: "5e5cb512e90bd40017385305",
},
},
onCompleted: (data) => {setAllNewComments( data.getPost.comments )}
要求:
我想在 useEffect 中第一次自动调用查询,然后在函数中手动调用。
Issue: Invarient Violation: Too many re-renders.
const [getComment, { loading, data }] = useLazyQuery(getCommentsQuery);
useEffect(() => {
getComment({
variables: {
input: {
id: "5e5cb512e90bd40017385305",
},
},
});
}, []);
if (data && data.getPost) {
var allNewComments = data.getPost.comments;
setAllComments(allNewComments); // re-renders
}
setState
导致了这个问题,我假设。
'Body parts' 的功能组件对于每个更改都是 运行,需要条件(或 useEffect
挂钩)来阻止意外行为。
只是不要将 useState
用于 allComments
?您可以使用 f.e.
const allNewComments = (data && data.getPost) ? data.getPost.comments : [];
...如果你想遍历 allNewComments
如果您仍然想使用 useState
(与 useLazyQuery
组合)...在 onCompleted
option/handler 中使用它,例如:
const [getComment, { loading, data }] = useLazyQuery(getCommentsQuery, {
variables: {
input: {
id: "5e5cb512e90bd40017385305",
},
},
onCompleted: (data) => {setAllNewComments( data.getPost.comments )}