P粉1830770972023-08-19 11:59:00
You can simply change this line in the addMoreData
function
setLoadedData((prev) => [...prev, ...newData]);
for
setLoadedData([...loadedData, ...newData]);
This will cause the state to be updated based on the value when it is currently rendered, because the second useEffect
run time the component has not yet re-rendered, so the changes made by the first component have not yet been reflected, so loadedData
has not been updated yet.
When you use the functional form to update, prev
is the real-time value of the state. It is normal for you to encounter this situation when using strict mode in development.
Finally, get rid of isLoading
, it won't help fix the problem.
Note: When strict mode is enabled, it is more recommended to use the setState function form, but it is not recommended in useEffect
because this hook will run when the component is mounted. twice.
Additionally, when you include data.length
and loadedData.length
in the dependency array, this will cause useEffect
when any of those values change will be triggered.