我有2个函数,函数
uploadFile
将文件图像上传到firebase,然后通过setState
存储返回的url,函数saveTeam
向/new-team-member
发送请求,负载包括返回的url
const uploadFile = async () => {
const imageRef = storageRef(storage, `images/${UniqueComponentId()}`);
uploadBytes(imageRef, team.image)
.then((snapshot) => {
getDownloadURL(snapshot.ref)
.then((url) => {
setTeam({ ...team, url: url || team.image });
})
.catch((error) => {
console.log(error.message);
});
})
.catch((error) => {
console.log(error.message);
});
};
const saveTeam = async () => {
setSubmitted(true);
let _teams = [...teams];
let _team = { ...team };
if (team.id) {
await fetch('https://bunaq-api.vercel.app/api/edit-team-member', {
method: 'PUT',
body: JSON.stringify(team),
headers: { 'Content-Type': 'application/json' },
});
const index = findIndexById(team.id);
_teams[index] = _team;
toast.current.show({
severity: 'success',
summary: 'Successful',
detail: t('adminTeamPage.new.toastUpdated'),
life: 5000,
});
} else {
fetch('https://bunaq-api.vercel.app/api/new-team-member', {
method: 'POST',
body: JSON.stringify(team),
headers: { 'Content-Type': 'application/json' },
});
_teams.unshift(_team);
// location.reload();
toast.current.show({
severity: 'success',
summary: 'Successful',
detail: t('adminTeamPage.new.toastCreated'),
life: 5000,
});
}
setTeams(_teams);
setTeamDialog(false);
setTeam(emptyTeam);
};
const saveTeamMain = async () => {
await uploadFile();
saveTeam();
};
<button onClick={saveTeamMain}>Save</button>;
但是当我第一次单击
Save
时它没有执行任何操作,然后在第二次单击时触发该功能,为什么会发生这种情况?
您必须单击两次的原因是,即使您等待
uploadFile
,由于上传文件使用.then
和.catch
,它会立即返回并在saveTeam
完成之前立即运行uploadFile
。因此 uploadFile
中发生的所有状态设置都发生在 saveTeam
运行之后。
您应该将
uploadFile
转换为await 语法。
const uploadFile = async () => {
const imageRef = storageRef(storage, `images/${UniqueComponentId()}`);
try{
const snapshot = await uploadBytes(imageRef, team.image)
const url = await getDownloadUrl(snapshot.ref)
setTeam({...team, url:url || team.image})
return
}catch(err){
console.log(err.message)
}
};