React不断重复调用一个函数。

huangapple go评论73阅读模式
英文:

React keeps calling a function repeatedly

问题

我有一个React页面,其中有一个从API中获取数据的函数,该函数在一个循环中执行。当满足特定条件时,循环终止。到目前为止,一切都按预期工作。

export default function Data() {
    ...
    ...
    needMore = true
    var loadData = async () => {
        ...
        while (needMore) {
            var result = await fetch('http://localhost:6000/api/data');
            dataRow = await result.json();
            addItems(offset, dataRow);
            if (dataRow.length < batchSize) {
                ...
                needMore = false
                break;
            }
        };
        console.log("Completed.");
    }
    loadData();


    return (
        <div className="ag-theme-balham" style={{ width: '100%' }}>
            <Stack spacing={2}>
                <AgGridReact
                    ...
                    defaultColDef={defaultColDef} />
            </Stack>
        </div>
    );
}

然而,问题是函数 loadData 一直不断地被调用,从而创建了一个无限循环。

我可以看到完整的数据已经被获取了一次,并且在控制台中我也可以看到我记录的 Completed.,但是立即函数再次被调用了,我不确定为什么以及如何停止这个循环。

英文:

I have a react page with a function to fetch data from API in a loop. The loop terminates when a certain condition is met. Till here everything keeps working as expected.

export default function Data() {
    ...
    ...
    needMore = true
    var loadData = async () =&gt; {
		...
        while (needMore) {
            var result = await fetch(&#39;http://localhost:6000/api/data&#39;);
            dataRow = await result.json();
            addItems(offset, dataRow);
            if (dataRow.length &lt; bacthSize) {
				...
				needMore = false
                break;
            }
        };
        console.log(&quot;Completed.&quot;);
    }
    loadData();


    return (
        &lt;div className=&quot;ag-theme-balham&quot; style={{ width: &#39;100%&#39; }}&gt;
            &lt;Stack spacing={2}&gt;
                &lt;AgGridReact
					...
				defaultColDef={defaultColDef} /&gt;
            &lt;/Stack&gt;
        &lt;/div&gt;
    );
}

However, the issue is that the function loadData repeatedly keeps getting called hence creating a indefinite loop.

I can see the complete data has been fetched once and in console I can also see Completed. which I am logging, but immediately that the function gets called again, which I am not sure why and how can I stop this?

答案1

得分: 1

是的,这就是React的工作方式。当你调用loadData时,它会执行该函数,然后addItems会更新状态。更新状态将重新渲染组件,然后再次调用loadData。它将从组件的开头执行到结尾。你需要使用React的生命周期钩子 - useEffect

useEffect(() => {
    loadData()
}, [])

useEffect的第二个参数是它的依赖项。查看这个链接以获取详细文档:
react useEffect

英文:

Yes, that's how react works. when you call loadData it will run the function and addItems will update the state. updating state will re-render the component and it will again call load data.
It will execute from the beginning of the component to the end.
You need to use React lifecycle hook - useEffect.

useEffect(()=&gt; {
    loaddata()
}, [])

the second argument of useEffect is its dependencies.
check this link for detailed doc
react useEffect

huangapple
  • 本文由 发表于 2023年7月17日 12:34:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76701508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定