从 React 应用程序执行突变时出现问题

Problem performing a mutations from react app

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>

这是我的表格

你可以这样做

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 given code is just to for reference. I am assuming you need to add both thing from single form. if you need to add them separately you can just split code in to 2 forms and 2 mutation component.

如有疑问请评论。