【发布时间】:2021-10-13 12:26:38
【问题描述】:
总结一下,我正在使用 React js 创建一个报价生成器。使用 React axios 从模拟 API 获取数据。
但是,当我尝试显示报价时,它给了我上述错误
我得到错误的行:{quotes[quoteIndex].quote}
(quotes) 被数据填充 (quoteIndex) 基本上是数组中的索引 (.quote) 是数据中的属性
请查找相关代码
// sample from .json file data
"quotes": [
{
"id":0,
"quote": "Genius is one percent inspiration and ninety-nine percent perspiration.",
"author": "Thomas Edison"
},
{
"id":1,
"quote": "You can observe a lot just by watching.",
"author": "Yogi Berra"
}
]
}
const [quotes, setQuotes] = useState([]);
const [quoteIndex, setQuoteIndex] = useState(0);
// fetching the data
const getData = async() =>{
try{
const response = await Axios.get("/quotes");
if(response && response.data){
setQuotes(response.data);
console.log(response.data);
}
}catch(error){
console.log(error);
}
}
//this inside the return statement
<div className="styleQuote">
<h3 className="styleText" >{quotes[quoteIndex].quote}</h3>
</div>
【问题讨论】:
标签: javascript reactjs axios fetch undefined