React Apollo 从缓存中加载数据然后发出请求

React Apollo load data from cache and then make request

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

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

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

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__typname 定义的对象应该以规范化形式正确缓存。您可以使用 React 开发工具检查缓存 details/state/internals(数据存储)(100% 确定)。

I want Apollo to first load the data from the cache and then make a request and then update the data and reload the Component if the result ist different from the cache data.

缓存优先是默认策略。

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

<Query/> 组件创建一个可观察对象,将在缓存数据更新时自动刷新(f.e。从另一个组件突变后)。