我在控制台中始终收到以下消息,“未捕获(承诺)TypeError:无法读取未定义的属性'length'”
quotesData.quotes应该是数组的键,但是,我不确定为什么其length属性未定义。
quotesData应该是一个类似于以下内容的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
});
})
}
答案 0 :(得分:0)
因为诺言解析为响应对象。尝试做:
import configparser
StatMod = 20
config = configparser.ConfigParser()
config.read('Database.ini')
for section in config.sections():
for k, v in config[section].items():
if 'infostat' in k: # configparses squashes case
print(f"[{section}]")
print(f"InfoStat={int(v) * StatMod}")
答案 1 :(得分:0)
因此,所需的数据实际上将位于响应的.data
属性上。因此,如果您像这样修复代码,就可以了:)
getQuote() {
let _this = this;
_this.serverRequest =
axios
.get("https://raw.githubusercontent.com/dwgillette/quotes/master/library")
.then(function(q) {
quotesData = q.data;
console.log(quotesData);
let newQuote = quotesData.quotes[Math.floor(Math.random() * quotesData.quotes.length)];
_this.setState({
quote: newQuote.quote,
author: newQuote.author
});
})
}
答案 2 :(得分:0)
Here is a screenshot of the response object you are getting back.
我重构了您的代码,使其正常工作。您需要使用res.data。
getQuote = () => {axios.get("https://raw.githubusercontent.com/dwgillette/quotes/master/library")
.then(res => {
let newQuote =
res.data.quotes[Math.floor(Math.random() * res.data.quotes.length)];
this.setState({
quote: newQuote.quote,
author: newQuote.author
});
});
};