Axios变得不确定 [英] Axios gets undefined

查看:81
本文介绍了Axios变得不确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有React组件FetchQoute,该组件应该从提供的URL中获取响应,但它显示的是 undefined ?

I have React component FetchQoute which is supposed to get response from the provided URL, but it shows undefined instead ?

class FetchQuote extends Component {
  constructor(props) {
    super(props);    
    this.state = {
      jokes: []
    };    
  }

  componentDidMount() {
    console.log(res.value); //undefined
    axios.get('https://api.icndb.com/jokes/random')
      .then((res) => {       
        this.setState({data:res.value.joke});//error TypeError: Cannot read property 'joke' of undefined
      })

  }

}

可以轻松地在浏览器中测试该URL,以正确返回JSON数据,包括res.value.joke

That URL can be easily tested in browser to return JSON data correctly, including res.value.joke

推荐答案

浏览器中的JSON响应是什么样的?axios在data属性下返回响应数据.

What's the JSON response look like in the browser? axios returns response data under the data attribute.

例如,如果您的JSON响应如下:

For example if your JSON response looks like:

{ "value": 
    { "joke": "lol"} 
}

然后您将以类似的方式访问它

Then you would access it like

axios.get('https://api.icndb.com/jokes/random')
      .then((response) => {       
        console.log(response.data.value.joke);
      })

这篇关于Axios变得不确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆