【问题标题】:how to access axios using react如何使用 react 访问 axios
【发布时间】:2020-08-13 11:42:27
【问题描述】:

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

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

【问题讨论】:

    标签: reactjs object axios state


    【解决方案1】:

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

    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])
    

    【讨论】:

    • 谢谢先生,它的工作原理就是 isLoading 需要为 false 才能呈现内容谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-07-07
    • 2018-12-24
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2021-07-12
    相关资源
    最近更新 更多