【发布时间】:2021-10-15 21:48:53
【问题描述】:
我已经按照阿波罗文档(https://www.apollographql.com/docs/react/pagination/cursor-based/#relay-style-cursor-pagination)通过以下方式实现了relayStylePagination():
index.js:
const httpLink=new HttpLink({
uri:'https://api.github.com/graphql',
headers:{
authorization: 'Bearer -'
}
})
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
repositories:relayStylePagination()
},
},
},
});
const client=new ApolloClient({
link:httpLink,
cache
})
ReactDOM.render(
<ApolloProvider client={client}>
<React.StrictMode>
<App />
</React.StrictMode>
</ApolloProvider>,
document.getElementById('root')
);
App.js:
const App=()=> {
const {loading,error,data,fetchMore}=useQuery(GET_REPOSITORIES_OF_CURRENT_USER,{
variables:{login:"rwieruch"}
})
if (loading) return <h1>Loading...</h1>
if (error) return <p>Error...</p>
console.log(data.user.repositories.edges)
console.log(data)
const pageInfo=data.user.repositories.pageInfo
console.log(pageInfo)
return(
<div>
<RepositoryList repositories={data.user.repositories} onLoadMore={()=>
{return fetchMore({
variables:{
after: data.user.repositories.pageInfo.endCursor,
}
})}
}
/>
</div>
)
}
按钮在子组件中是如何呈现的:
<button onClick={onLoadMore}>Hey</button>
最后是gql查询:
const GET_REPOSITORIES_OF_CURRENT_USER = gql`
query getUser($login:String!,$after:String){
user (login:$login){
repositories(
first: 10,
after:$after
) {
edges {
node {
id
name
url
descriptionHTML
primaryLanguage {
name
}
owner {
login
url
}
stargazers {
totalCount
}
viewerHasStarred
watchers {
totalCount
}
viewerSubscription
}
}
pageInfo{
endCursor
hasNextPage
}
}
}
}
`;
问题是当我按下带有对应于 fetchMore 的 onClick 属性的按钮时,什么都没有获取。此外,我的控制台中没有错误——它什么也没做。你能告诉我为什么吗?我已经想弄清楚几个小时了。谢谢!
【问题讨论】:
-
你能检查一下你传递的函数
onLoadMore是否真的被调用了?您可以通过在 return 语句之前记录来做到这一点。 -
@Herku 你好!是的,它正在被调用,我尝试在函数中登录 endCursor,一切都很好......
-
@Herku Apollo 在控制台中给出了以下警告,但它没有被标记为错误
Cache data may be lost when replacing the user field of a Query object. To address this problem (which is not a bug in Apollo Client), either ensure all objects of type User have an ID or a custom merge function, or define a custom merge function for the Query.user field, so InMemoryCache can safely merge these objects:我已经在用户查询中添加了一个 id 并且警告消失了,但它仍然没有获取更多.. -
好的,我现在写一个答案,我想我明白你的问题了
-
@Herku 非常感谢!
标签: graphql apollo-client