reactjs - 在事件处理程序中调用 Hook (useMutation) 错误 : "Hooks can only be called inside of the body of a function component"

标签 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

它是一个钩子(Hook),因为 useMutation 的定义如下:

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

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

最佳答案

So, how do I call a mutation inside an event handler?

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

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

关于reactjs - 在事件处理程序中调用 Hook (useMutation) 错误 : "Hooks can only be called inside of the body of a function component",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56212612/

相关文章:

reactjs - React 中的导入对象未定义

javascript - 在三元运算符中 React Router <Link>

graphql - 如何将 apollo 客户端 fetchMore updateQuery 转换为 apollo 缓存合并功能?

reactjs - React 自定义 Hook 使用 useRef 在第一次调用组件加载时返回 null?

reactjs - 使用钩子(Hook)编辑 React Material 表

javascript - 为什么所需的检查在日期选择器中不起作用?

java - 使用 Dropwizard 提供多个静态资源

javascript - 更新状态时如何防止模态重新渲染?

javascript - Apollo 客户端本地状态缓存竞争条件?

laravel - 您将 CSRF token 放在 Relay/GraphQL 中的什么位置?