阿波罗的<Mutation>
组件通常运行良好,但有时您需要在render()
方法之外调用突变。
在某些情况下,您可以简单地传递突变函数,如下所示:
import React, { Component } from "react";
import { DO_MUTATION } from "./mutations";
import { Mutation } from "react-apollo";
export default class MyComponent extends Component {
render() {
return (
<Mutation mutation={DO_MUTATION}>
{(doMutation) => (
<Button
onPress={() => {
this.handleSomething(doMutation);
}}
/>
)}
</Mutation>
);
}
handleSomething = (doMutation) => {
/* DO SOME STUFF */
doMutation();
};
}
但在其他情况下,这不是一个非常合理的选择,例如:
import React, { Component } from "react";
import { DO_MUTATION } from "./mutations";
import { Mutation } from "react-apollo";
import SomeLibrary from "SomeLibrary";
export default class MyComponent extends Component {
render() {
return (
<Mutation mutation={DO_MUTATION}>
{(doMutation) => (
<Button
onPress={() => {
SomeLibrary.addListener(this.listenerHandler);
}}
/>
)}
</Mutation>
);
}
listenerHandler = () => {
/* HOW DO I DO MUTATIONS HERE? */
};
}
在这些情况下如何进行突变?
React Hooks 更新 (2020-12-18):
如果您使用的是 Apollo v3+ 和功能性 React 组件,现在有一个使用 Apollo 提供的useMutation()
钩子的更干净的解决方案:
import React from "react";
import { useMutation } from "@apollo/client";
import SomeLibrary from "SomeLibrary";
import { DO_MUTATION } from "./mutations";
export default function MyComponent() {
const [doMutation, { data }] = useMutation(DO_MUTATION);
let listenerHandler = () => {
doMutation({
variables: {
some_var: "some_val",
},
});
};
return (
<button
onPress={() => {
SomeLibrary.addListener(listenerHandler);
}}
/>
);
}
此外,官方文件说:
useMutation React 钩子是执行突变的主要 API 在阿波罗应用程序中。
在 Apollo 中,现在使用钩子比 HOC 更受欢迎,所以如果可以的话,使用useMutation()
可能是个好主意。
您可以在以下位置阅读有关useMutation
的文档: https://www.apollographql.com/docs/react/data/mutations/
原答案:
react-apollo
包括两个称为graphql()
和withApollo()
的 HOC,可用于完成此操作。
两者之间的区别在阿波罗的文档中描述为:
如果你想知道什么时候使用 Apollo() 以及什么时候使用 graphql(),答案是大多数时候你会想要使用 graphql()。 graphql() 提供了处理 GraphQL 数据所需的许多高级功能。只有当你想要没有任何其他功能的 GraphQL 客户端时,你才应该使用 Apollo()。
当graphql()
提供突变时,它将添加一个this.props.mutate()
函数,可以像这样使用:
import React, { Component } from "react";
import { DO_MUTATION } from "./mutations";
import { graphql } from "react-apollo";
import SomeLibrary from "SomeLibrary";
export class MyComponent extends Component {
render() {
return (
<Button
onPress={() => {
SomeLibrary.addListener(this.listenerHandler);
}}
/>
);
}
listenerHandler = () => {
this.props.mutate({
variables: {
some_var: "some_val",
},
});
};
}
export default graphql(DO_MUTATION)(MyComponent);
withApollo()
类似,但提供了一个直接使用this.props.client
。突变可以像这样执行:
import React, { Component } from "react";
import { DO_MUTATION } from "./mutations";
import { withApollo } from "react-apollo";
import SomeLibrary from "SomeLibrary";
export class MyComponent extends Component {
render() {
return (
<Button
onPress={() => {
SomeLibrary.addListener(this.listenerHandler);
}}
/>
);
}
listenerHandler = () => {
this.props.client.mutate({
mutation: DO_MUTATION,
variables: {
some_var: "some_val",
},
});
};
}
export default withApollo(MyComponent);