【问题标题】:Apollo with redux-persist带有 redux-persist 的 Apollo
【发布时间】:2017-08-23 14:25:12
【问题描述】:

我集成了 react-apollo,用于从我的 GraphQL 服务器获取数据到我的 react 本机应用程序中。我使用 redux-perist 来持久化和补充 redux 存储。

但我不知道如何为我的阿波罗状态补充水分。

有人知道我该怎么做吗?

谢谢

【问题讨论】:

    标签: react-native react-redux apollo react-apollo


    【解决方案1】:

    您可以使用redux-persistautoRehydrate 功能。它将异步运行 REHYDRATE 类型的操作,除非您将它们列入黑名单,否则它将重新水化所有商店。

    如果您尝试执行之前执行的查询,Apollo 将首先检查您的 Redux 存储,您应该会看到一个 APOLLO_QUERY_RESULT_CLIENT 操作执行(意味着它从客户端存储返回而不是查询服务器)。您可以修改fetchPolicy 以指定查询如何获取其数据(仅限网络、缓存优先等)

    这是一个基本设置:

    import React, { Component } from 'react';
    import { ApolloProvider } from 'react-apollo';
    import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
    import ApolloClient, { createNetworkInterface } from 'apollo-client';
    import { persistStore, autoRehydrate } from 'redux-persist';
    import { AsyncStorage } from 'react-native';
    
    const networkInterface = createNetworkInterface({ uri: 'http://localhost:8080/graphql' });
    
    export const client = new ApolloClient({
      networkInterface: networkInterface,
    });
    
    const store = createStore(
      combineReducers({
        apollo: client.reducer(),
      }),
      {}, // initial state
      compose(
        applyMiddleware(client.middleware()),
        autoRehydrate(),
      ),
    );
    
    // persistent storage
    persistStore(store, {
      storage: AsyncStorage, // or whatever storage you want
    });
    
    export default class App extends Component {
      render() {
        return (
          <ApolloProvider store={store} client={client}>
            <YourApp />
          </ApolloProvider>
        );
      }
    }
    

    【讨论】:

    • 谢谢@srtucker22 !!我的问题是我使用了 devTools(),然后使用了 autoRehydrate()。出于某种奇怪的原因,这不起作用,我必须先做 autoRehydrate () 然后 devTools () .. 现在它起作用了!
    • @Carol 祝福你。您的解决方案刚刚结束了 3 天的咬指甲和拉头发。将autoRehydrate() 放在(typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined' || process.env.NODE_ENV !== 'production') ? window.__REDUX_DEVTOOLS_EXTENSION__() : (f) =&gt; f, 之前,解析的数据在页面重新加载后被保留。
    猜你喜欢
    • 1970-01-01
    • 2020-01-06
    • 2020-07-12
    • 2021-09-08
    • 2018-08-28
    • 2023-02-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    相关资源
    最近更新 更多