收到此错误:错误:重新渲染过多。 React限制了渲染次数以防止无限循环

时间:2020-05-05 17:49:19

标签: graphql react-hooks hook react-apollo react-apollo-hooks

我有一个步进窗体,可以使用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个令牌?

1 个答案:

答案 0 :(得分:1)

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

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

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

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