根据Apollo Docs,我希望将ApolloClient中的mutate()
函数放入属于我的react组件的props中。这是正确/首选的方式吗?
class myComponent extends React.Component {
constructor(props) {
super(props);
this.mutate = props.client.mutate();
};
}
答案 0 :(得分:3)
如果你想使用apollo客户端动态调用变异,你可以这样使用它:
import { withApollo } from 'react-apollo';
class myComponent extends React.Component {
constructor(props) {
super(props);
this.mutate = props.client.mutate;
}
onClick = () => {
this.mutate({
mutation: gql `${<define your graphql mutation>}`,
variables: { ... },
}).then(...);
}
...
}
export default withApollo(MyComponent);
否则我建议你用graphql
静态定义你的变异,然后调用变异:
class MyComponent extends React.Component {
onClick = () => {
this.props.mutate({ variables: { ... } }).then(....);
}
...
}
const yourGraphqlMutation = gql `${<define your graphql mutation>}`;
export default graphql(yourGraphqlMutation)(MyComponent);