首页 > 解决方案 > 如何使用 react 访问 axios

问题描述

我使用反应创建报价生成器。我无法访问数组内的对象。查看所有数组很好,但是当我尝试指定我需要的键时,它说无法读取未定义的属性

class Quote extends React.Component{
   state = {
       quotes : []

   }


componentDidMount(){
axios.get('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json').then(res=>{
this.setState({
    quotes: res.data.quotes
    })
})
}
render(){
    console.log(this.state.quotes[0])

这是正在运行的代码,它显示的结果如下:

   {quote: "Life isn’t about getting and having, it’s about giving and being.", author: "Kevin Kruse"}

但是当我改用它时:

   console.log(this.state.quotes[0].quote)

错误说:

   TypeError: Cannot read property 'quote' of undefined

标签: reactjsobjectaxiosstate

解决方案


数据渲染最初不可用,并在初始渲染后异步加载。您要么需要使用加载状态,要么有条件地访问状态

class Quote extends React.Component{
   state = {
       quotes : []
       isLoading: true,
   }


componentDidMount(){

    axios.get('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json').then(res=>{
        this.setState({
            quotes: res.data.quotes,
            isLoading: false,
            })
        })

}
render(){
    if(this.state.isLoading) return <div>Loading...</div>

    console.log(this.state.quotes[0])

推荐阅读