reactjs - 如何使用 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
解决方案
数据渲染最初不可用,并在初始渲染后异步加载。您要么需要使用加载状态,要么有条件地访问状态
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])
推荐阅读
- php - 什么时候应该使用 hasOne(),什么时候应该使用 belongsTo()?
- pandas - 为什么 pandas.date_range() 生成月份这么慢?
- javascript - Django:如何将模板列表传递给 JavaScript onclick 方法?
- c# - 等待一个函数调用将完成 c#
- android - 失败 - 未安装 0
- opengl-es - 使用模板缓冲区渲染时纹理中的 OpenGL 透明度
- node.js - 请求 http://registry.npmjs.org/check 失败,原因:连接 ECONNREFUSED
- php - 让管理表单监听来自子管理员的验证
- webpack - Vue Pre-render SPA - 根覆盖模板文件
- python - 从 HDF5 迁移到 NetCDF 以存储 pyomo 模型结果