我有一个运行验证的函数,并根据检查结果设置状态变量。我需要传递变量以通过API调用上传。
我的问题是,当我需要在api调用中传递更新的serviceSelected
变量时,状态变量没有更新,并且正在传递初始状态(null)。
我将如何解决这个问题?
当前代码
const [serviceSelected, setServiceSelected] = useState(null)
function checkServicesSelected () {
if (photography === true && video === false && drone === false){
setServiceSelected(PhotographyService);
} else if(photography === true && video === true && drone === false){
setServiceSelected(PhotographyVideoService);
} else if (photography === true && video === true && drone === true){
setServiceSelected(allThreeServices);
} else if (photography === false && video === true && drone === false){
setServiceSelected(VideoService);
} else if (photography === false && video === true && drone === true){
setServiceSelected(VideoDroneService);
} else if (photography === true && video === false && drone === true){
setServiceSelected(PhotographyDroneService);
} else if (photography === false && video === false && drone === true){
setServiceSelected(DroneService);
}
}
/// first runs the check, then makes an api call.
async function completeApplication() {
setShowSubmitForm(true);
try {
/// run check
await checkServicesSelected()
/// pass info to uploadInfo Function
const UploadProspectInfo = await UploadInfo({service: serviceSelected})
} catch (e) {
alert(e.message);
}
setShowThankYou(true);
}
更新的代码现在可以使用
useEffect(() => {
if(serviceSelected){
UploadInfo({service: serviceSelected})
.catch(function (e) {
alert(e.message);
});
setShowThankYou(true)
}
}, [serviceSelected]);
function completeApplication() {
setShowSubmitForm(true);
checkServicesSelected();
}
答案 0 :(得分:1)
答案 1 :(得分:1)
setServiceSelected重新呈现该组件,因此在此行上将有旧的serviceSelected值:
const UploadProspectInfo = await UploadInfo({service: serviceSelected})
因此,如果要在状态中存储serviceSelected值(用于进行api调用之外的其他目的),则有两个选择,您必须使用useEffect:
useEffect(() => {
if(serviceSelected){
UploadInfo({ service: serviceSelected })
.catch(function (e) {
alert(e.message);
});
}
}, [serviceSelected]);
/// first runs the check, then makes an api call.
function completeApplication() {
setShowSubmitForm(true);
checkServicesSelected();
setShowThankYou(true);
}
但是,如果您不想以状态存储,则可以使checkServicesSelected函数为纯函数,然后返回选定的服务,而不是以状态存储。