简体   繁体   English

在 useCallback 中更新状态 - React JS

[英]Updating state inside useCallback - React JS

How can I restructure this code to allow a state update inside the useCallback function?如何重构此代码以允许在useCallback函数内进行状态更新?

Here's what is executed first:这是首先执行的内容:

useEffect(() => {
    getData();
}, [getData]); // errors if getData is left (missing dependency error)

In the getData function, I pass a state variable ( lastDoc ) to getSomething() as a parameter.getData函数中,我将一个状态变量 ( lastDoc getSomething()作为参数传递给getSomething() It stores the last document/database row for pagination.它存储用于分页的最后一个文档/数据库行。

const [lastDoc, setLastDoc] = useState(null);

const getData = useCallback(async() => {
    const data = await getSomething(lastDoc);
    setLastDoc(data.lastDoc); // useSate function
}, [getSomething, lastDoc]);

This, at the moment, just causes an infinite loop where the getData function is re-rendered once setLastDoc updates the lastDoc variable, as getData has lastDoc as a dependency.目前,这只会导致无限循环,一旦setLastDoc更新lastDoc变量,就会重新呈现getData函数,因为getDatalastDoc作为依赖项。 If I remove the lastDoc dependency, I get the missing dependency error, which I understand to be an important error to listen to.如果我删除lastDoc依赖项,我会收到缺少依赖项错误,我认为这是一个重要的要听的错误。

I think a null-check might be sufficient.我认为空检查可能就足够了。

useEffect(() => {
    if(lastDoc === null){
        getData();
    }
}, [getData, lastDoc]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM