我的状态
const [isEnabled, setIsEnabled] = useState(false);
GetUser()
async function getUser() {
verifyEmail(getTokenIdFromURL); /* Updates field in backend from false -> true */
await Axios.get(URL+getTokenIdFromURL).then(function (response) {
setIsEnabled(response.data.enabled) /* Checks if updated value is true and updates state */
})
}
UseEffect()
useEffect(() => {
getUser();
return () => {
/* */
};
}, []);
返回
return (
<div className="emailVerificationWrapper">
{isEnabled ? <h1>true</h1> : <EmailVerificationFailed /> }
</div>
)
返回在 setIsEnabled
之前呈现,这导致最终结果为false
,但是如果我重新加载网站(或控制台日志)状态值),则将其设置为true
(根据需要)。
在应用程序呈现
setIsEnabled
之前,如何使return
更新状态?
答案 0 :(得分:1)
useEffect运行后,发布渲染返回语句。您需要具有加载状态才能等待数据被获取
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
getUser();
return () => {
/* */
};
}, []);
function getUser() {
verifyEmail(getTokenIdFromURL); /* Updates field in backend from false -> true */
Axios.get(URL+getTokenIdFromURL).then(function (response) {
setIsLoading(false);
setIsEnabled(response.data.enabled)
})
}
if(isLoading) {
return <div>Loading...</div>
}
return (
<div className="emailVerificationWrapper">
{isEnabled ? <h1>true</h1> : <EmailVerificationFailed /> }
</div>
)
答案 1 :(得分:0)
请这样更新:
async function getUser() {
verifyEmail(getTokenIdFromURL); /* Updates field in backend from false -> true */
const response = await Axios.get(URL+getTokenIdFromURL)
setIsEnabled(response.data.enabled) /* Checks if updated value is true and updates state */
}
答案 2 :(得分:0)
useEffect(async () => {
await getUser();
return () => {
/* */
};
}, []);