gpt4 book ai didi

javascript - fetchMore 是如何向组件返回数据的?

转载 作者:行者123 更新时间:2023-12-03 07:20:15 24 4
gpt4 key购买 nike

我正在尝试使用 React Apollo ( https://www.apollographql.com/docs/react/data/pagination/#cursor-based ) 遵循基于光标的分页示例,但我正在努力解决渲染原始数据的组件如何获取新的(附加的)数据。
这就是我们获取原始数据并将其传递给组件的方式:

const { data: { comments, cursor }, loading, fetchMore } = useQuery(
MORE_COMMENTS_QUERY
);

<Comments
entries={comments || []}
onLoadMore={...}
/>
我不确定 fetchMore功能有效。
onLoadMore={() =>
fetchMore({
query: MORE_COMMENTS_QUERY,
variables: { cursor: cursor },
updateQuery: (previousResult, { fetchMoreResult }) => {
const previousEntry = previousResult.entry;
const newComments = fetchMoreResult.moreComments.comments;
const newCursor = fetchMoreResult.moreComments.cursor;

return {
// By returning `cursor` here, we update the `fetchMore` function
// to the new cursor.
cursor: newCursor,
entry: {
// Put the new comments in the front of the list
comments: [...newComments, ...previousEntry.comments]
},
__typename: previousEntry.__typename
};
}
})
}
据我了解,是的,一旦我的组件调用此 onLoadMore函数(例如使用按钮的 onClick),它将根据新光标获取数据。
我的问题是这个。如果这太简单了,我很抱歉,我不理解一些基本的东西。
组件如何获取新数据?
我知道数据在那里,因为我在控制台记录了 newComments (就我而言,这不是新评论,但你明白了。)我看到了新数据!但是那些新的评论,它们是如何返回到需要数据的组件的呢?如果我再次单击该按钮,它仍然停留在与以前相同的光标上。
我在这里想念什么?

最佳答案

这取决于您如何处理偏移量。我将尝试为您简化一个示例。
这是我成功使用的简化组件:

const PlayerStats = () => {
const { data, loading, fetchMore } = useQuery(CUMULATIVE_STATS, {
variables: sortVars,
})

const players = data.GetCumulativeStats

const loadMore = () => {
fetchMore({
variables: { offset: players.length },
updateQuery: (prevResult, { fetchMoreResult }) => {
if (!fetchMoreResult) return prevResult
return {
...prevResult,
GetCumulativeStats: [
...prevResult.GetCumulativeStats,
...fetchMoreResult.GetCumulativeStats,
],
}
},
})
}
我的 CUMULATIVE_STATS查询默认返回 50 行。我将该结果数组的长度传递给我的 fetchMore查询为 offset .所以当我执行 CUMULATIVE_STATSfetchMore ,查询的变量都是 sortVarsoffset .
我在后端的解析器处理 offset因此,例如,如果它是 50,它会忽略查询的前 50 个结果并从那里返回下一个 50(即第 51-100 行)。
然后在 updateQuery我有两个可用的对象: prevResultfetchMoreResult .在这一点上,我只是使用扩展运算符将它们组合起来。如果没有返回新结果,则返回以前的结果。
当我多次获取时, players.length 的结果变为 100 而不是 50。这是我的新偏移量,下次我调用 fetchMore 时将查询新数据.

关于javascript - fetchMore 是如何向组件返回数据的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62558430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com