组合使用突变与查询几乎相同。带有以下表格的简单(未经测试)示例。表单组件有一个文本框并接收一个 submitForm 属性。此属性通过 apollo HoC 包装器映射到 UpdateThing 突变,并传递必要的参数。
Form.jsx
export default class Form extends React.Component {
state = {
name: this.props.name
};
handleSubmit = (e) => {
e.preventDefault();
this.props.submitForm(this.props.id, this.state.name);
};
handleChangeName = (e) => {
this.setState({
name: e.target.value
});
};
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="text" id="name" name="name" onChange={this.handleChangeName} value={this.state.name} />
<button type="submit">Submit</button>
</form>
);
}
}
FormContainer.jsx
const withQuery = ... // Assume query code here
const withUpdateThing = graphql(gql`
mutation UpdateThing($id: ID!, $name: String!) {
updateThing(id: $id, name: $name) {
id
name
}
}
`, {
props: ({ mutate }) => ({
submitForm: (id, name) => mutate({ variables: { id, name } })
})
});
export default compose(withQuery, withUpdateThing)(Form);
然后可以通过简单地使用<FormContainer id={1} />
. withQuery
注入name
道具,withUpdateThing
注入submitForm(id, name)
道具。