英文:
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 () => {
		...
        while (needMore) {
            var result = await fetch('http://localhost:6000/api/data');
            dataRow = await result.json();
            addItems(offset, dataRow);
            if (dataRow.length < bacthSize) {
				...
				needMore = false
                break;
            }
        };
        console.log("Completed.");
    }
    loadData();
    return (
        <div className="ag-theme-balham" style={{ width: '100%' }}>
            <Stack spacing={2}>
                <AgGridReact
					...
				defaultColDef={defaultColDef} />
            </Stack>
        </div>
    );
}
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(()=> {
    loaddata()
}, [])
the second argument of useEffect is its dependencies.
check this link for detailed doc
react useEffect
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论