我遇到了一个问题,垃圾邮件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并将项目设置为活动,因为当时,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
的值发生变化时,就会调用useEffect
的返回函数,因此,如果在开始获取数据后单击showCustom
,则在设置数据之前,它会将fetchCanceled
翻转为true。
另外:您不需要setItems
的函数形式,除非您使用items
的当前值来更新该值。