【发布时间】: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