首页 > 解决方案 > 无法弄清楚为什么数组长度未定义

问题描述

我在控制台中不断收到以下消息,“未捕获(承诺)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
            });
        })
}

标签: reactjsaxios

解决方案


因为承诺解析为响应对象。尝试做:

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
        });
    })
}

推荐阅读