【发布时间】:2022-01-18 23:27:41
【问题描述】:
我已阅读 StackOveflow 的旧相关帖子,但似乎 API 已更改。我将 React 与 GraphQL 和 Strapi 一起使用。我的 graphql 查询中有 ID 参数。尽管我检查了文档,但我无法看到此警告的来源。
所有后端数据集合的 ID 都由 Strapi 管理。
如果你能帮忙,我会欠你很多的!
我收到的警告是这样的:
Cache data may be lost when replacing the attributes field of a CategoryEntity object.
To address this problem (which is not a bug in Apollo Client), either ensure all objects of type Category have an ID or a custom merge function, or define a custom merge function for the CategoryEntity.attributes field, so InMemoryCache can safely merge these objects:
existing: {"__typename":"Category","name":"Worms","reviews({\"sort\":\"createdAt:desc\"})":{"__typename":"ReviewRelationResponseCollection","data":[{"__ref":"ReviewEntity:5"}]}}
incoming: {"__typename":"Category","name":"Worms"}
For more information about these options, please refer to the documentation:
* Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers
* Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects
请在下面找到我的完整代码:
import React from 'react'
import { useQuery, gql } from '@apollo/client'
import { useParams, Link } from 'react-router-dom'
const CATEGORY= gql`
query GetCategory($id: ID!) {
category(id: $id) {
data
{
id
attributes
{
name
reviews (sort: "createdAt:desc") {
data
{
id
attributes
{
title
body
rating
createdAt
categories{
data
{
id
attributes{
name
}
}
}
}
}
}
}
}
}
}
`
export default function Category() {
const { id } = useParams()
const { loading, error, data } = useQuery(CATEGORY, {
variables: { id: id }
})
if (loading) return <p>Loading...</p>
if (error) return <p>`Error! ${error}`</p>
console.log(data)
return (
<div>
<h2>{ data.category.data.attributes.name } Games</h2>
{data.category.data.attributes.reviews.data.map(review => (
<div key={review.id} className="review-card">
<div className="rating">{review.attributes.rating}</div>
<h2>{review.attributes.title}</h2>
<h5>{review.attributes.createdAt.substring(0, 10)}</h5>
{review.attributes.categories.data.map(c => (
<small key={c.id}>{c.attributes.name}</small>
))}
<p>{review.attributes.body.substring(0, 200)}...</p>
<Link to={`/details/${review.id}`}>Read more</Link>
</div>
))}
</div>
)
}
【问题讨论】: