Reactjs Can';我不明白为什么数组长度没有定义

Reactjs Can';我不明白为什么数组长度没有定义,reactjs,axios,Reactjs,Axios,我在控制台中不断收到以下消息,“Uncaught(in promise)TypeError:无法读取未定义的属性'length'” 但是,quotesData.quotes应该是数组的键,所以我不确定为什么它的length属性未定义 quotesData应该是一个JSON对象,看起来像:{“quotes”:[Object1,Object2,…等]} 我使用axios的方式有问题吗?一般来说,我对编程还是很陌生,对react.js也很陌生 getQuote() { let _this =

我在控制台中不断收到以下消息,“Uncaught(in promise)TypeError:无法读取未定义的属性'length'”

但是,quotesData.quotes应该是数组的键,所以我不确定为什么它的length属性未定义

quotesData应该是一个JSON对象,看起来像:{“quotes”:[Object1,Object2,…等]}

我使用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
        });
    })
}

因此,您需要的数据实际上将位于响应的
.data
属性上。因此,如果您像这样修复代码,您将很高兴:)

我重构了你的代码以使其正常工作。您需要使用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
  });
});
};

这个打印输出console.log(quotesData)是什么@jsdeveloper它打印JSON对象这修复了它!非常感谢你!啊,我知道是我丢失的
。数据。谢谢如果你看我的链接,你就会明白你收到的确切承诺。当您进行api调用时,您得到的不仅仅是您要求的数据。
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
  });
});
};