reactjs - 使用 apollo 客户端 fetchMore Apollo Client 多次触发相同的查询并附加数据
问题描述
我将一个类组件转换为一个函数组件以使用 React Hooks。graphQl 查询调用如下:
const { data, error, loading, fetchMore } = useQuery(getAll, {
variables: {
code: props.code,
type: props.type,
page: 0
}
});
fetchMore
功能是我正在寻找的。我检查了几个教程,它们都实现了onClick触发器的fetchMore
功能。
我的问题是:
是否可以在fetchMore
不触发事件的情况下调用?以便在设置变量时有条件地调用它?
更新 1
正如建议的那样,我尝试了useEffect
钩子。这是代码:
useEffect(() => {
if(data != null) {
const { nextLink } = data.list.nextLink;
if(nextLink !== []){
fetchMore({
variables: {
code: props.code,
type: props.type,
page: page+1
},
updateQuery: (prevResult, { fetchMoreResult }) => {
fetchMoreResult.list = [
...prevResult.list,
...fetchMoreResult.list
];
return fetchMoreResult;
}
});
}
}
});
但是它只调用一次查询。如何多次触发该查询,直到nextLink不为空?然后更新结果?
更新 2
经过一些工作,我可以调用所有页面并获取数据。这就是我所做的。
我在后端查询中添加了page字段,该字段用作要来回传递给查询调用的变量。此外,这个页面变量在每次调用时都会增加。此外,仅当nextLink为空时才调用 fetchmore 函数。但是,当前页面只显示最后一页结果,因为新结果替换了旧数据。
这是代码:
let [hasNext, setHasNext] = useState(true);
useEffect(() => {
if(data != null) {
const { nextLink, page } = data.list;
let isNext = (nextLink !== "") ? true : false;
setHasNext(isNext);
if(hasNext){
const { data } = fetchMore({
variables: {
code: props.code,
type: props.type,
page: parseInt(page)
},
updateQuery: (prevResult, { fetchMoreResult }) => {
fetchMoreResult = {
...prevResult,
...fetchMoreResult,
};
return fetchMoreResult;
}
});
}
}
});
扩展运算符似乎不起作用。如何将获取的新数据附加到旧结果中?
解决方案
经过一些尝试,这是我的解决方案。正如评论中所建议的,要多次触发相同的查询,我应该fetchMore
在useEffect
钩子内使用。
这是代码:
useEffect(() => {
if(data != null) {
if(data.list !== []){
const { nextLink, page } = data.list;
let isNext = (nextLink !== "") ? true : false;
setHasNext(isNext);
if(hasNext && page != null){
const { data } = fetchMore({
variables: {
code: props.code,
type: props.type,
page: page
},
updateQuery: (prev, { fetchMoreResult }) => {
if (!fetchMoreResult) {
return prev;
}
return {
list: {
...prev.list,
...fetchMoreResult.list,
array: [
...prev.list.array,
...fetchMoreResult.list.array,
],
},
};
}
});
} else {
setLoadingState(false);
}
}
}
});
graphQL 查询如下:
query($code: String, $type: Int, $page: Int) {
list(code: $code, type: $type, page: $page) {
array {
ID
title
field_firstname
field_lastname
}
nextLink
page
}
}
推荐阅读
- unity3d - Unity 3d 使用代码编辑(更改)主模型
- python - Python大写字符串列表
- bash - 使用 bash 将内容附加到 ROOT 文件?
- android - 错误:使用 JsonReader.setLenient(true) 在第 1 行第 1 列路径 $ 接受格式错误的 JSON
- c# - C# 用户击键未注册
- python - 在循环内合并数据框 - 熊猫很慢
- amazon-web-services - AWS 自定义授权方超时
- sql - SQL中子查询的替代方案?
- svn - svn propset svn:auto-props :递归地为整个存储库设置多个文件,如何?
- python - Django ModelForm 和 mock.patch.object 打破单元测试隔离?