0

我有一个步进表单,它使用 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 个令牌?

4

1 回答 1

1

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

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

解决方案是将这段代码放入 useEffect 并在数据更改时运行它

useEffect(() => {
   if (appMutationResponse.data) {
      submitToken();
   }
}, [appMutationResponse.data])
于 2020-05-05T17:59:40.113 回答