在变量 for 循环中运行 react hook [英] Run react hook inside variable for-loop

查看:186
本文介绍了在变量 for 循环中运行 react hook的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是用例.我们单独的 AJAX 调用在一个钩子后面(我们使用 apollo 钩子).但是,有时我们需要进行可变数量的调用(可变 for 循环).初始 AJAX 调用决定了对另一个端点进行多少变量调用.不幸的是,这段代码没有运行(React 运行时错误):

Here's the use case. Our individual AJAX calls are behind a hook (we use apollo hooks). However, sometimes we need to make a variable number of calls (a variable for-loop). An initial AJAX calls determines how many variable calls to make to another endpoint. Unfortunately, this code does not run (React runtime error):

https://jsfiddle.net/dm3b2Lgh/

我看过另一个问题,但给定的方法不起作用:为什么不能在循环或嵌套函数内调用 React Hooks?

I've looked at this other question but the given approach does not work: Why can't React Hooks be called inside loops or nested function?

有没有办法让这个工作?

Is there a way to make this work?

function useInitialAjaxCall() {
    const [result, setResult] = React.useState(0);
  React.useEffect(() => {
    const resultSize = Math.floor((Math.random() * 100) + 1);
    Promise.resolve().then(() => setResult(
            resultSize
    ))
  }, [])
  return result;
}

function useMockAjaxCall(i) {
    const [result, setResult] = React.useState();
  React.useEffect(() => {
    Promise.resolve().then(() => setResult(i));
  }, [i])
  return result;
}

function useMakeNCalls(n) {
   return [...Array(n)].map((_, i) => useMockAjaxCall(i));
}

function useCombineAjaxCalls(n) {
    const resultArray = useMakeNCalls(n);
    const resultCombined = React.useMemo(() => {
    return resultArray.reduce((total, cur) => total + cur, 0);
  }, [resultArray])
  return resultCombined;
}

function Hello(props) {
  const initial = useInitialAjaxCall();
  const count = useCombineAjaxCalls(
        initial
  );
  return (
  <div>
  <div>{initial}</div>
  <div>{count}</div>
  </div>
  );
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

);}ReactDOM.render(<Hello name="World"/>,document.getElementById('容器'));

推荐答案

原始问题询问了一个固定的-循环:

if we call useState inside a loop where the number of iterations doen't change over the time

如果我们在迭代次数不随时间变化的循环中调用 useState

However, in your code, useInitialAjaxCall() will return undefined during first render (because useEffect is asynchronous - it will be executed AFTER the first render).

但是,在您的代码中,useInitialAjaxCall() 将在第一次渲染期间返回 undefined(因为 useEffect 是异步的 - 它将在之后执行第一次渲染).

Then, useCombineAjaxCalls(undefined) will call useMakeNCalls(undefined) which will call useMockAjaxCall(0), calling useState only once.

然后,useCombineAjaxCalls(undefined) 将调用 useMakeNCalls(undefined),后者将调用 useMockAjaxCall(0),调用 useState 仅一次.

In the end of first render, initial will be undefined and count will be NaN.

在第一次渲染结束时,initial 将是 undefined 并且 count 将是 NaN.

假设 resultSize 与 1 不同,在下一次渲染中,您的代码将尝试调用 useState 与 1 不同的次数,这是不可能的,如中所述原来的问题.

Assuming resultSize is different from 1, in the next render, your code will try to call useState different number of times than 1, which is not possible as explained in the original question.

不可能在变量 for 循环内运行 react hook" - 但您可以创建 1 个状态,即一个数组.

It is NOT possible to "Run react hook inside variable for-loop" - but you can create 1 state that is an array.

这篇关于在变量 for 循环中运行 react hook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆