如果用户单击我的React应用程序内的按钮,则会从API提取某些数据。如果在API调用完成之前单击了另一个按钮,则不应应用回调函数。不幸的是,状态(在我的代码示例中为“ loading”)在回调内部没有正确的值。我在做什么错了?
const [apartments, setApartments] = useState(emptyFeatureCollection);
const [loading, setLoading] = useState(true);
function getApartments() {
fetch(`https://any-api-endpoint.com`)
.then(response => response.json())
.then(data => {
if (loading) setApartments(data);
})
.catch(error => console.error(error));
}
}
useEffect(() => {
setLoading(false);
}, [apartments]);
function clickStartButton() {
setLoading(true);
getApartments();
}
function clickCancelButton() {
setLoading(false);
}
答案 0 :(得分:2)
这里的问题是回调代码:
data => {
if (loading) setApartments(data);
}
当getApartments()
为假时,在loading
的原始关闭上下文中调用。
这意味着回调仅能看到或“继承”先前的loading
状态,并且由于setAppartments()
依赖于更新的loading
状态,因此网络请求中的数据永远不会已应用。
一种需要对您的代码进行最少更改的简单解决方案是将回调传递给setLoading()
。这样做将使您可以访问当前的loading
状态(即组件的状态,而不是执行回调中关闭的状态)。这样,您就可以确定是否应更新公寓数据:
function getApartments() {
/* Block fetch if currently loading */
if (loading) {
return;
}
/* Update loading state. Blocks future requests while this one
is in progress */
setLoading(true);
fetch(`https://any-api-endpoint.com`)
.then(response => response.json())
.then(data => {
/* Access the true current loading state via callback parameter */
setLoading(currLoading => {
/* currLoading is the true loading state of the component, ie
not that of the closure that getApartnment() was called */
if (currLoading) {
/* Set the apartments data seeing the component is in the
loading state */
setApartments(data);
}
/* Update the loading state to false */
return false;
});
})
.catch(error => {
console.error(error);
/* Reset loading state to false */
setLoading(false);
});
}
这里是working example for you to see in action。希望有帮助!