我想在fetchMore
到达底部时onscroll
个数据。我遇到的问题是,我得到重复的元素,因此控制台也对我大喊大叫,unique element keys
也是如此。我在graphql游乐场中获取了正确的数据,所以这在我的react
组件中是个问题。这种逻辑有意义吗?怎么了?
class App extends Component {
isBottom = (fetchMore, data) => {
window.onscroll = () => {
if (
data &&
data.infiniteScrollMovies &&
data.infiniteScrollMovies.hasMore &&
window.innerHeight + document.documentElement.scrollTop === document.documentElement.offsetHeight
) {
console.log('YES!')
this.fetchMoreData(fetchMore, data)
}
}
}
fetchMoreData = (fetchMore, data) => {
fetchMore({
variables: {
offset: data.infiniteScrollMovies.newOffset,
},
updateQuery: (prev, { fetchMoreResult }) => {
if (!fetchMoreResult) return prev
return {
...fetchMoreResult,
infiniteScrollMovies: {
...fetchMoreResult.infiniteScrollMovies,
movies: [...prev.infiniteScrollMovies.movies, ...fetchMoreResult.infiniteScrollMovies.movies],
},
}
},
})
}
render() {
return (
<div className="flex flex-column">
<Query query={ALL_MOVIES} notifyOnNetworkStatusChange={true} fetchPolicy="network-only">
{({ data, loading, error, fetchMore }) => {
if (error) return <h1>{error.message}</h1>
this.isBottom(fetchMore, data)
return (
<div>
{data &&
data.infiniteScrollMovies &&
data.infiniteScrollMovies.movies.map(m => (
<article key={m.id}>
// ... rendering an element
</article>
))}
<div>{loading && <h1 className="red text-center">Loading...</h1>}</div>
这是我的查询:
export const ALL_MOVIES = gql`
query infiniteScrollMovies($offset: Int) {
infiniteScrollMovies(offset: $offset, limit: 16) {
movies {
image_url
title
id
}
hasMore
newOffset
}
}
`
答案 0 :(得分:1)
使用variables
中的updataeQuery
参数来处理这种情况,基本上,如果已经完成,则需要防止在缓存中追加。
将您的updateQuery更改为以下
updateQuery: (prev, { variables, fetchMoreResult }) => {
// Return the prev values, if it allready has the length specified by offset
// thereby preventing duplicate values in cache.
if (!fetchMoreResult ||
prev.infiniteScrollMovies.movies.length > variables.offset)
return prev
答案 1 :(得分:0)
尝试禁用notifyOnNetworkStatusChange选项