【发布时间】: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