【发布时间】:2021-02-18 09:06:11
【问题描述】:
我将一个类组件转换为一个函数组件以使用 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;
}
});
}
}
});
扩展运算符 似乎不起作用。如何将获取的新数据附加到旧结果中?
【问题讨论】:
-
为什么是 compose,而不是 hooks?有点“古老的技术”...为什么不从 react-apollo 编写...github.com/git-ly/sportsstore/blob/… - 检查数据/道具流
-
我还是不用钩子了,不然得重写组件。我正在转向使用新组件的钩子。没有钩子就没有办法吗?使用
Query组件可能吗? -
INHO 组件不是更好的选择......我没有选择使用它,我跳过了这个选项(因为不可读,限制等)从 HOC 到钩子
-
使用 useEffect 挂钩
-
ehhh ...*'在设置变量时有条件地调用'* ...这里有什么变化? ... useState ... 间隔更新,直到某些条件
标签: reactjs graphql react-apollo apollo-client