在事件处理程序错误内调用一个钩子(useMutation):“钩子只能在函数组件的主体内部调用”

时间:2019-05-19 22:47:04

标签: reactjs graphql react-hooks mutation

我想在事件处理程序中使用一个突变。我的事件定义如下:

(JSX attribute) onOk?: ((e: React.MouseEvent<any, MouseEvent>) => void) | undefined

这就是我称呼客户的突变

export const IMPORT_INFO_MUTATION = gql`
  mutation ImportPolicy($data: ImportPolicyInput!) {
    importPolicy(data:$data)
    {
      _id
      name
    }
 }

最终我这样称呼它:

      onOk={() => {

        useImportPolicyMutation({
          variables: {
            data: {
              jsonData: JSON.parse(importPolicyData)
            }
          },
        })
      }

`不必担心突变中的变量和参数。他们很好。问题是出现以下错误:

Unhandled Rejection (Invariant Violation): Invalid hook call. Hooks can only 
be called inside of the body of a function component. This could happen for 
one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)

2. You might be breaking the Rules of Hooks

3. You might have more than one copy of React in the same app

这是一个钩子,因为useMutation的定义如下:

  return ReactApolloHooks.useMutation<ImportPolicyMutation, ImportPolicyMutationVariables>(
   ImportPolicyDocument,
baseOptions
 )

那么,我该如何在事件处理程序中调用突变?

1 个答案:

答案 0 :(得分:1)

  

那么,我该如何在事件处理程序中调用突变?

  1. 挂钩仅适用于功能组件,而不适用于基于类的挂钩(使用阿波罗client.mutation()<Mutation/>组件)
  2. useMutation返回旨在按需使用的函数-此函数必须在事件处理程序中使用,而不是整个useMutation

react-apollo-hooks项目描述包含与事件处理程序一起使用的usemutation的示例。

相关问题