您可以使用withApollo()
导出的装饰器apollo-client
作为组件内的道具访问客户端。通过上下文向其子组件ApolloProvider
公开。高阶组件访问on 上下文并将client
其作为道具传递给它的子组件。withApollo()
client
因此,如果auth.lock()
函数由某种类型的 UI 交互或 React 生命周期方法之一触发,您可以访问该client
组件中的 ,并直接在组件中调用突变或将其作为参数传递给调用auth.lock()
.
但是,由于您想访问client
React 树的外部,您必须以client
不同的方式访问。
或者,您可以导出client
作为道具传递的相同内容,ApolloProvider
并将其导入应用程序中需要使用的任何位置。请注意,此单例模式不适用于服务器端渲染。例子:
根.jsx
import React from 'react';
import { Router, browserHistory } from 'react-router';
import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { syncHistoryWithStore } from 'react-router-redux';
import routes from './routes';
const networkInterface = createNetworkInterface({
uri: '/graphql',
opts: {
credentials: 'same-origin'
}
});
export const client = new ApolloClient({
networkInterface
});
export const store = configureStore(browserHistory, client);
export const history = syncHistoryWithStore(browserHistory, store);
export default function Root() {
<ApolloProvider client={client} store={store}>
<Router
history={history}
routes={routes}
/>
</ApolloProvider>
}
一些其他的module.js
import { client } from 'app/root';
export default function login(username, password) {
return client.mutate({
// ...mutationStuff
});
}