const ADD_TODO = gql`
mutation AddTodo($type: String!) {
addTodo(type: $type) {
name
}
}
`;
const ADD_AUTHOR = gql`
mutation AddAuthor($type: String!) {
addAuthor(type: $type) {
name
}
}
`;
我有以上两种变异,可以在数据库中添加数据。我正在捕获bookval和authorval变量中的突变所需的名称字段。这些变量分别传递给AddBook和AddAuthor函数
AddBook(bookval) {
const [addBook, { data }] = useMutation(ADD_BOOK);
addBook({ variables: { type: bookval } });
};
AddAuthor(authorval) {
const [addAuthor, { data }] = useMutation(ADD_AUTHOR);
addAuthor({ variables: { type: authorval } });
};
这是我在表单提交中调用的功能。但是我得到一个错误,即只能在函数组件内部调用Hooks
<form>
<p>Book Name</p>
<input
type='text'
ref={ (value) => this.book = value}
placeholder="enter book's name"/>
<br/>
<p>Author Name</p>
<input
type='text'
ref={ (value) => this.author = value}
placeholder="enter author's name"/>
<br/>
<br/>
<button onClick={this.getValues.bind(this)}>Donate</button>
</form>
这是我的表格
答案 0 :(得分:1)
您可以这样做
return (
<Mutation mutation={ADD_BOOK}>
{(addBook, { data }) => (
<Mutation mutation={ADD_AUTHOR}>
{(addAuthor, { data }) => (
<div>
<form
onSubmit={e => {
e.preventDefault();
addBook({ variables: { type: this.book.value } });
addAuthor({ variables: { type: this.author.value } });
this.book.value = "";
this.author.value = "";
}}
>
<input
ref={node => {
this.book = node;
}}
/>
<input
ref={node => {
this.author = node;
}}
/>
<button type="submit">Add Item</button>
</form>
</div>
)}
</Mutation>
)}
</Mutation>
);
@note给出的代码仅供参考。我假设您需要从单一表单中添加这两种内容。如果您需要分别添加它们,则可以将代码分为2种形式和2种突变成分。
如有疑问,请发表评论。