Javascript 反应无限循环中的聚焦输入

Javascript 反应无限循环中的聚焦输入,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我正在创建一个简单的测验,它只是一行中的一组输入,在其中键入答案。我正在尝试将自动焦点添加到这些输入元素中,如果最后一个输入已提交,则循环返回到第一个输入,并跳过已回答的问题。我已经设法获得了我想要的功能,但是当用户提供了太多不正确的asnwer时,所有的输入都被设置为disabled,我得到了“超过了最大调用堆栈大小”,我不知道为什么。以下是我的职能: const getNextElement = (idx: number): HTMLInputElement | null => {

我正在创建一个简单的测验,它只是一行中的一组输入,在其中键入答案。我正在尝试将自动焦点添加到这些输入元素中,如果最后一个输入已提交,则循环返回到第一个输入,并跳过已回答的问题。我已经设法获得了我想要的功能,但是当用户提供了太多不正确的asnwer时,所有的输入都被设置为disabled,我得到了“超过了最大调用堆栈大小”,我不知道为什么。以下是我的职能:

const getNextElement = (idx: number): HTMLInputElement | null => {
    //if all questions are done and disabled, return null
    if (totalFinished > focusRefs.current.length - 2) {
      return null;
    }

    const nextItem = focusRefs.current[idx];

    //if we are at the last element in focus refs, go back to start
    if (nextItem === undefined) {
      return getNextElement(0);
    }

    //if the input is disabled, try focusing on the next one
    //this one seems to be the source of the infinite loop
    if (isOn && nextItem.disabled) {
      return getNextElement(idx + 1);
    }

    return nextItem;
  };

  const focusInput = (name: string) => {
    //find current element index
    const foundElIdx = focusRefs.current.findIndex((el: HTMLInputElement) => {
      return el.name === name;
    });

    //get next element
    const nextElement = getNextElement(foundElIdx + 1);

    //TS check
    if (nextElement === null) {
      return;
    }

    nextElement.focus();
  };

我用注释标记了有问题的块。即使在redux中将isOn设置为false时,它也会以某种方式被触发,因为组件渲染的次数太多了。因此,已达到最大调用堆栈。您必须为整个组件提供代码,以找出问题所在。如果您使用的是useEffect,则它可以位于useEffect中。这可能是因为您直接在主功能组件中而不是在包装器函数中设置状态。无限循环还有其他几个原因。禁用状态或isOn状态何时以及如何标记Turns其他组件(我将焦点函数作为道具传递给它)是错误的来源。我设置了一个计时器来回答其中的一个问题,当计时器过期时,答案被验证,下一个元素被聚焦,依此类推。当isOn变为false时,我忘了清除计时器,因此在一段时间后启动了获取焦点的下一个元素的函数,没有有效元素,因此出现了无限循环。