react usestate使用接口返回数据报undefined

457 阅读1分钟
  1. 现象:得到后端返回数据后,通过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>

image.png 2. 原因:setState操作是异步的,当render使用时变量还未保存完成,所以报undefined

  1. 解决:使用变量前先进行判断
<Button>{captchaData?.codeNum}</Button>