【发布时间】:2017-11-04 05:18:44
【问题描述】:
我正在尝试使用 react-apollo 制作多语言单页应用程序。当前语言环境存储在 redux 存储中。问题是我必须将每个组件连接到 redux 才能将语言环境变量传递给查询。这种重复的代码看起来是多余的。我无法将语言环境硬编码到查询中,因为它对于不同的用户可能会有所不同。我需要动态传递默认值。有什么想法吗?
【问题讨论】:
标签: reactjs graphql apollo react-apollo
我正在尝试使用 react-apollo 制作多语言单页应用程序。当前语言环境存储在 redux 存储中。问题是我必须将每个组件连接到 redux 才能将语言环境变量传递给查询。这种重复的代码看起来是多余的。我无法将语言环境硬编码到查询中,因为它对于不同的用户可能会有所不同。我需要动态传递默认值。有什么想法吗?
【问题讨论】:
标签: reactjs graphql apollo react-apollo
您可以使用 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;
【讨论】: