【问题标题】:React apollo default query variable from redux store反应来自 redux 商店的 apollo 默认查询变量
【发布时间】:2017-11-04 05:18:44
【问题描述】:

我正在尝试使用 react-apollo 制作多语言单页应用程序。当前语言环境存储在 redux 存储中。问题是我必须将每个组件连接到 redux 才能将语言环境变量传递给查询。这种重复的代码看起来是多余的。我无法将语言环境硬编码到查询中,因为它对于不同的用户可能会有所不同。我需要动态传递默认值。有什么想法吗?

【问题讨论】:

    标签: reactjs graphql apollo react-apollo


    【解决方案1】:

    您可以使用 apollo 客户端的中间件将语言环境作为标头添加到您发送到服务器的每个请求中。如果您使用的是浏览器,则将语言环境存储在 localStorage 中;如果您使用的是 react native,则将其存储在 asyncStorage 中。

    import ApolloClient, { createNetworkInterface } from 'apollo-client';
    import { GRAPHQL_API_DEV } from './api';
    import { checkForLocale } from '../../utils/locale';
    
    const networkInterface = createNetworkInterface({
      uri: GRAPHQL_API_DEV
    });
    
    networkInterface.use([{
      applyMiddleware(req, next) {
        // Create the header object if needed.
        if (!req.options.headers) {
          req.options.headers = {};
        }
    
        // get the locale token from Async storage
        // and assign it to the request object
        checkForLocale()
        .then(LOCALE => {
          req.options.headers.custom-header = LOCALE;
          next();
        })
        .catch(error => {
          req.options.headers.custom-header = null;
          next();
        })
      }
    }]);
    
    const client = new ApolloClient({
      networkInterface,
      dataIdFromObject: o => o.id
    });
    
    export default client;
    

    【讨论】:

      猜你喜欢
      • 2018-09-14
      • 1970-01-01
      • 2018-06-13
      • 2021-07-14
      • 2017-12-04
      • 1970-01-01
      • 2019-09-17
      • 2014-11-09
      • 2018-12-24
      相关资源
      最近更新 更多