您可以使用从apollo-client
导出的withApollo()
装饰器作为组件内的道具访问客户端。 ApolloProvider
通过上下文将client
公开给其子组件。高阶组件在上下文上访问client
,并将其作为道具传递给其子项。
因此,如果auth.lock()
函数是由某种类型的UI交互或某个React生命周期方法触发的,则可以访问该组件中的client
,并直接在组件中调用突变或将其作为参数传递通过调用auth.lock()
的函数。
但是,由于您想要访问React树以外的client
,因此必须以不同的方式访问client
。
或者,您可以导出与ApolloProvider
相同的client
,并将其导入到需要在应用程序中使用的任何位置。请注意,此单例模式不适用于服务器端呈现。例如:
root.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
});
}
我可以做client.query以同样的方式? – Vivek