【问题标题】:delayed state update in useEffect with api call使用 api 调用在 useEffect 中延迟状态更新
【发布时间】:2020-12-30 16:21:48
【问题描述】:

我遇到了一个问题,即发送垃圾邮件的 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>
         );

问题是,如果我将 showCustom 从 true 切换为 false,它将启动 api 调用,但如果我将其快速切换回 true,它将完成 api 并将项目设置为实时,因为在那一刻,自定义是假的,即使我的 showCustom 后来是真的。

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

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

【问题讨论】:

  • 您在问如何中止 API 调用吗?你有自定义的钩子
  • 如果您包含您正在谈论的自定义挂钩之一的示例,您的评论会更有帮助。

标签: reactjs setstate use-effect


【解决方案1】:

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

    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 的值发生变化时,都会调用useEffect 的返回函数,因此如果在开始获取数据后单击showCustom,它将在设置数据之前将fetchCanceled 翻转为true。

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

【讨论】:

    猜你喜欢
    • 2022-01-22
    • 2019-12-07
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2020-06-07
    • 2023-01-14
    相关资源
    最近更新 更多