Reactjs 使用api调用延迟状态更新生效

Reactjs 使用api调用延迟状态更新生效,reactjs,setstate,use-effect,Reactjs,Setstate,Use Effect,我有一个问题,垃圾邮件2按钮更新状态不正确 export default function App() { const [items, setItems] = useState(null); const [showCustom, setShowCustom] = useState(false); const customItems = useSelector(flipBoardItems); const dispatch = useDispatch();

我有一个问题,垃圾邮件2按钮更新状态不正确

export default function App() {
    const [items, setItems] = useState(null);
    const [showCustom, setShowCustom] = useState(false);
    const customItems = useSelector(flipBoardItems);
    const dispatch = useDispatch();

    useEffect(() => {
        (async () => {
            if (!showCustom) {
                const data = await getFlipBoardContent();
                setItems(() => data);
            } else {
                setItems(() => Object.values(customItems));
            }
        })();
    }, [customItems, showCustom]);

    return (
        <div>
            <Paper>
                <Toolbar>
                    <Button onClick={() => setShowCustom(true)}>Show Custom</Button>
                    <Button onClick={() => setShowCustom(false)}>Show Live</Button>
                </Toolbar>
            </Paper>
                </div>
         );
导出默认函数App(){
const[items,setItems]=useState(null);
const[showCustom,setShowCustom]=useState(false);
const customItems=useSelector(flipBoardItems);
const dispatch=usedpatch();
useffect(()=>{
(异步()=>{
如果(!showCustom){
常量数据=等待getFlipBoardContent();
设置项(()=>数据);
}否则{
setItems(()=>Object.values(customItems));
}
})();
},[customItems,showCustom]);
返回(
setShowCustom(true)}>显示自定义
setShowCustom(false)}>Show Live
);
问题是,如果我将showCustom从true切换到false,它将启动一个api调用,但如果我将其快速切换回true,它将完成api并将项设置为live,因为在那个时刻,custom为false,即使我的showCustom稍后为true

我已经看到了多个关于如何在组件卸载时执行此操作的示例,但没有找到与我的问题相关的任何内容


我的问题是,当showCustom为true时,如何防止useEffect api调用更新项目状态?

您可以执行类似于在组件卸载时取消的操作:

    useEffect(() => {
        let fetchCanceled = false;

        (async () => {
            if (!showCustom) {
                const data = await getFlipBoardContent();

                if (fetchCanceled) {
                  return;
                }

                setItems(data);
            } else {
                setItems(Object.values(customItems));
            }
        })();

        return () => {
          fetchCanceled = true;
        };
    }, [customItems, showCustom]);
只要
showCustom
的值发生变化,就会调用
useffect
的返回函数,因此,如果您在开始提取数据后单击
showCustom
,它将在设置数据之前将
fetchCanceled
翻转为true


另外:您不需要函数形式的
setItems
,除非您使用
items
的当前值来更新该值。

您想知道如何中止API调用吗?你有一个自定义的钩子,如果你在评论中加入一个你正在谈论的自定义钩子的例子,你的评论会更有帮助。