如何防止axios在状态更新之前发布



我遇到一个问题,post请求没有发送更新的currentVideo状态,因为setState似乎是非阻塞的。如何让axios等待状态设置?

const nextVideo = () => {
if (videoList.indexOf(currentVideo) < videoList.length - 1) {
setCurrentVideo(videoList[videoList.indexOf(currentVideo) + 1]);
setLoading(true);
axios
.post(`${BACK_PORT}/videos/download`, currentVideo)
.then(function (response) {
if (response.data) {
setLoading(false);
} else {
console.log("waiting...");
}
})
.catch(function (error) {
alert(error)
});
} else {
alert("This is the last video");
}
};

使用一个变量并将currentvideo值存储在其中。然后在两个位置都使用该变量,即用于设置状态和进行axios调用。

const nextVideo = () => {
if (videoList.indexOf(currentVideo) < videoList.length - 1) {
let currentVideo = videoList[videoList.indexOf(currentVideo) + 1] //change here
setCurrentVideo(currentVideo );
setLoading(true);
axios
.post(`${BACK_PORT}/videos/download`, currentVideo)
.then(function (response) {
if (response.data) {
setLoading(false);
} else {
console.log("waiting...");
}
})
.catch(function (error) {
alert(error)
});
} else {
alert("This is the last video");
}
};

最新更新