【问题标题】:React Apollo Client - query results mixing up in cacheReact Apollo Client - 查询结果在缓存中混合
【发布时间】:2022-01-09 18:43:54
【问题描述】:

我使用 apollo 客户端来获取书籍图表并使用中继式分页。以下NEW_BOOKS 查询和ALL_BOOKS 查询都可以独立工作。

目前,我在主页中使用NEW_BOOKS,在主页的弹出窗口中使用ALL_BOOKS。 当主页打开时NEW_BOOKS 加载正常。 当弹出窗口打开并获取ALL_BOOKS 时,newBooks 变为undefinedALL_BOOKS 查询的结果。

为什么会这样?

const { loading, data: newBooks, fetchMore, networkStatus } = useQuery(NEW_BOOKS, {
    variables: {
        first: PAGE_SIZE,
        after: endCursor
    },
    notifyOnNetworkStatusChange: true
});

const NEW_BOOKS = gql`query GetNewBooks($first:Int!, $after:String){
    books(
        first: $first, after: $after,
        filters: [
            {
                path: "isNew",
                value: true
            }
        ]
    ) {
        totalCount
        pageInfo {
            hasNextPage
            hasPreviousPage
            startCursor
            endCursor
        }
        edges {
            node {
                id
                name
                author {
                    id
                    name
                }
            }
        }
    }
}`;

-可按名称过滤的所有书籍查询

const { loading, data: filteredBooks, fetchMore, networkStatus } = useQuery(ALL_BOOKS, {
    variables: {
        first: PAGE_SIZE,
        after: endCursor,
        name: nameFilter
    },
    notifyOnNetworkStatusChange: true
});

const ALL_BOOKS = gql`query GetAllBooks($first:Int!, $after:String, $name:String){
    books(
        first: $first, after: $after,
        filters: [
            {
                path: "name",
                value: $name,
                type: "contains"
            }
        ]
    ) {
        totalCount
        pageInfo {
            hasNextPage
            hasPreviousPage
            startCursor
            endCursor
        }
        edges {
            node {
                id
                name
                copiesSold
                author {
                    id
                    name
                }
            }
        }
    }
}`;

正在使用的缓存是这样的,

const cache = new InMemoryCache({
    typePolicies: {
        Query: {
            fields: {
                books: relayStylePagination(),
            },
        }
    },
});

【问题讨论】:

    标签: reactjs apollo-client react-apollo


    【解决方案1】:

    当使用relayStylePagination 或类似的分页时,我们必须显式传递keyArgs

    A keyArgs: ["type"] 字段策略配置意味着 type 是缓存在访问该字段的值时应该考虑的唯一参数(除了字段名称和封闭对象的标识)。 keyArgs: false 配置禁用了通过参数区分字段值的整个系统,因此字段的值将仅由字段的名称(在某些 StoreObject 中)标识,而不附加任何序列化参数。 KeyArgs documentation here.

    const cache = new InMemoryCache({
        typePolicies: {
            Query: {
                fields: {
                    books: relayStylePagination(["name"]),
                },
            }
        },
    });
    

    【讨论】:

      猜你喜欢
      • 2020-02-11
      • 2022-12-22
      • 2020-10-22
      • 2021-02-23
      • 2021-02-13
      • 2019-03-30
      • 2022-10-16
      • 2020-12-24
      • 2020-12-17
      相关资源
      最近更新 更多