- 现象:得到后端返回数据后,通过setState将数据保存在了state中,在render中使用报undefined
const [captchaData,setCaptchaResData]=useState()
const changeCaptcha=()=>{
const currTime=new Date().getTime()
axios({
url:`http://localhost:3000/jshERP-boot/user/randomImage/${currTime}`,
type:'get',
data:{}
}).then(res=>{
if(res.status==200){
setCaptchaResData(res.data.data)
}
})
}
<Button>{captchaData.codeNum}</Button>
2. 原因:setState操作是异步的,当render使用时变量还未保存完成,所以报undefined
- 解决:使用变量前先进行判断
<Button>{captchaData?.codeNum}</Button>