Recieved this error: Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

Recieved this error: Error: Too many re-renders. React limits the number of renders to prevent an infinite loop

我有一个步进器表单,它使用 GraphQL/Apollo 和 React 在两个不同的地方插入数据。

代码如下:

    export function ProjectStep({classes, nextStep}) {

      const {loading, error, data} = useUserQuery();
      const organizationsArray = _.get(data, "user.organizations");
      const [projectName, setProjectName] = useState("");
      const [organization, setOrganization] = useState("");
      const [createProject, appMutationResponse] = useappInsertMutation();
      const [createToken, tokenMutationResponse] = usetokenInsertMutation();
      const submitForm = () => {
        const variables = {name: projectName, orgId: organization, description: ""};
        createProject({variables});
      };

      const submitToken = () => {
        const variables = {
          enable: true,
          lastUsed: Date.now().toString(),
          appId: appMutationResponse.data.appInsert.id,
          orgId: appMutationResponse.data.appInsert.orgId,
        };
        createToken({variables});
      };

      if (appMutationResponse.data) {
        submitToken();
      }
}

第一个插入在:

const submitForm = () => {
            const variables = {name: projectName, orgId: organization, description: ""};
            createProject({variables});
          };

第二个插入开始:

const submitToken = () => {
            const variables = {
              enable: true,
              lastUsed: Date.now().toString(),
              appId: appMutationResponse.data.appInsert.id,
              orgId: appMutationResponse.data.appInsert.orgId,
            };
            createToken({variables});
          };

这些事件在按钮中被调用:

 <Button variant="contained" color="primary" type='button' onClick={submitForm}>
    Next
 </Button>

但是,当我点击按钮时,出现了这个错误:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

当我访问我的数据库时,我看到使用这部分代码在一次调用中保存了 50 个令牌:

const submitToken = () => {
                const variables = {
                  enable: true,
                  lastUsed: Date.now().toString(),
                  appId: appMutationResponse.data.appInsert.id,
                  orgId: appMutationResponse.data.appInsert.orgId,
                };
                createToken({variables});
              };

我认为因为我使用的是挂钩,所以我得到了响应,而该响应给我带来了错误,问题是,为什么我在一次调用中保存和接收 50 个令牌?

您直接在渲染中编写了以下代码,因此当 appMutationResponse.data 可用时,如果调用触发重新渲染的 submitToken 函数,然后再次调用该函数会导致无限循环.

if (appMutationResponse.data) {
   submitToken();
}

解决方案是将此代码放在 useEffect 中,运行 将其放在数据更改中

useEffect(() => {
   if (appMutationResponse.data) {
      submitToken();
   }
}, [appMutationResponse.data])