使用react,apollo。
我想对状态中存储的id数量执行useUserQuery。目前,它只执行一次,因为ids[0]写在变量中。另外,我只能获得id[0]的数据。
我想执行useUserQuery的次数和状态中有id的次数一样多。
const [ids, setIds] = React.useState<string[]>([]);
const {data: {userData = null} = {}} = useUserQuery({
variables: {id: ids[0]},
skip: !ids,
});
不确定useUserQuery是什么意思,让我假设它是使用原始useQuery
的自定义钩子
一个可能的解决方案是使用手动触发的useLazyQuery
,否则你可以这样做:
let fetchId = useRef(0);
const {data: {userData = null} = {}, refetch} = useUserQuery({
variables: {id: ids[0]},
skip: !ids,
onComplete: () => {
if (++fetchId.current < ids.length)
refetch({id: fetchId.current})
}
});
在这种情况下,你也可以使用useState
,它会在更改时自动重取。