【问题标题】:React Apollo load data from cache and then make requestReact Apollo 从缓存中加载数据然后发出请求
【发布时间】:2019-10-05 03:35:00
【问题描述】:

您好,我对 React-Apollo 有疑问..

当我将 fetchPolicy 设置为缓存和网络时,我的 Apollo 每次都会发出新请求,并且不会从缓存中加载数据。

我希望 Apollo 先从缓存中加载数据,然后发出请求,如果结果与缓存数据不同,则更新数据并重新加载组件。

const client = new ApolloClient({
    connectToDevTools: true,
    cache,
    link: ApolloLink.from([
        stateLink,
        new HttpLink({
            uri: "..."
        })
    ]),
});
query user($userId: String) {
    user(_id: $userId) {
        __typename
        _id
        fullname
        username
        followed_by_viewer
        follows_viewer
        edge_followed_by {
            count
        }
        edge_follow {
            count
        }
    }
}
<Query query={GET_USER} variables={{ userId }} fetchPolicy={"cache-and-network"} partialRefetch={false} >
{({ data, loading, error, refetch }) => {

        if (error) return <Text>Error</Text>
        if (loading) return <Text>Loading</Text>

        let user = data.user;

        console.log(user);

        return (
            <ScrollView
                refreshControl={
                    <RefreshControl
                        refreshing={loading}
                        onRefresh={refetch}
                    />
                }>

                <View style={[s.gradientBar, { backgroundColor: profileColor }]} />

                <View style={s.nameInfos}>
                    <Text style={s.fullname}>{user.fullname}</Text>
                    <Text style={s.name}>@{user.username}</Text>
                </View>



            </ScrollView>
        )
    }}

</Query>

【问题讨论】:

  • 查询,类型?没有 id 道具?
  • @xadm 现在?够了吗?

标签: react-native graphql apollo react-apollo apollo-client


【解决方案1】:

使用_id__typname 定义的对象应该以规范化的形式正确缓存。您可以使用反应开发工具检查缓存详细信息/状态/内部(数据存储)(100% 确定)。

我希望 Apollo 先从缓存中加载数据,然后发出请求,如果结果与缓存数据不同,则更新数据并重新加载组件。

缓存优先是默认策略。

使用refetch(作为刷新)恕我直言强制网络请求 - 它是现有&lt;Query/&gt; 状态/进程的一部分,而不是单独的操作。缓存(仅)将被使用(无网络请求) f.e.当另一个实例或其他组件请求相同的数据范围(查询、变量)时。

&lt;Query/&gt; 组件创建一个 observable,将在缓存数据更新时自动刷新(例如,从另一个组件发生突变后)。

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2021-12-28
    相关资源
    最近更新 更多