如何从 graphql() 创建的高阶组件中获取突变结果



React Apollo Mutations允许我创建一个组件,该组件以{ data, loading, error }作为道具接受MutationResult: https://www.apollographql.com/docs/react/api/react-apollo.html#mutation-render-prop

现在,如果我要使用由graphql()创建的高阶组件

function MyComponent({ mutate }) {
return (
<button onClick={() => {
mutate({
variables: { foo: 42 },
});
}}>
Mutate
</button>
);
}
export default graphql(gql`mutation { ... }`)(MyComponent);

我的组件将只有mutate作为道具。如何{ data, loading, error }组件?

突变是一个承诺,因此您可以在 then 中接收值,并根据需要返回它们。 如果您有 async 和 await,则可以返回数据并使用 await,以便能够以同步风格的代码访问它。

function MyComponent({ mutate, setState }) {
return (
<button onClick={() => 
mutate({
variables: { foo: 42 },
}).then(data => {
// Process your data as needed here:
setState({ data });
}).catch(err => console.error('Our Error: ', err);
}>
Mutate
</button>
);
}
export default graphql(gql`mutation { ... }`)(MyComponent);

@allenylzhou

实际上,您可以在文档中阅读它。它说变异返回一个承诺。因此,您可以使用.then从突变或.catch中获取结果,以防出现错误。在加载的情况下,您可以使用组件状态来执行此操作,在突变之前调用setState({ loading: true}),在突变之后调用setState({ loading: false})。希望对您有所帮助!

最新更新