reactjs - 无法弄清楚为什么数组长度未定义
问题描述
我在控制台中不断收到以下消息,“未捕获(承诺)TypeError:无法读取未定义的属性'长度'”
但是,quotesData.quotes 应该是数组的键,所以我不确定为什么它的长度属性未定义。
quoteData 应该是一个 JSON 对象,如下所示: { "quotes": [Object1, Object2, ...etc.]}
我使用 axios 的方式有问题吗?一般来说,我对编程还是很陌生,对 react.js 也很陌生
getQuote() {
let _this = this;
_this.serverRequest =
axios
.get("https://raw.githubusercontent.com/dwgillette/quotes/master/library")
.then(function(quotesData) {
console.log(quotesData);
let newQuote = quotesData.quotes[Math.floor(Math.random() * quotesData.quotes.length)];
_this.setState({
quote: newQuote.quote,
author: newQuote.author
});
})
}
解决方案
因为承诺解析为响应对象。尝试做:
getQuote() {
let _this = this;
_this.serverRequest =
axios
.get("https://raw.githubusercontent.com/dwgillette/quotes/master/library")
.then(function(response) {
let newQuote = response.data.quotes[Math.floor(Math.random() * response.data.quotes.length)];
_this.setState({
quote: newQuote.quote,
author: newQuote.author
});
})
}
推荐阅读
- r - unique.default(x, nmax = nmax) 中的错误:unique() 仅适用于向量
- python - 从 x, y 坐标计算曲线下面积
- html - 将数据库中的数据显示到我的刀片页面中
- r - 如何在 R 中为 dplyr 中的配对行分配条件
- r - 以最有效的方式获取间隔期间的事件数
- spring-batch - 在春季批处理步骤执行期间获取数据
- scala - Scala ReactiveMongo 示例。遗漏的操作或隐含
- python - Python CSV如何删除第一行数据?
- php - 如何向 request()->all() 添加变量?(Laravel 6.0)
- javascript - v-for 渲染组件和
,如何只为一个组件实例更改它