在这个应用程序中,我尝试创建一个测验应用程序。
import React, { useState, useEffect, Component } from 'react';
const axios = require('axios').default;
const PlayQuiz = () => {
// declaring all the state here
const [questionsArray, setQuestionsArray] = useState([]);
// Using effects here
useEffect(() => {
axios({
method: 'get',
url: 'https://opentdb.com/api.php?amount=10',
}).then(res => {console.log(Object.values(res.data)[1]); setQuestionsArray(Object.values(res.data)[1])})
.catch(err => console.error(err))
}, []);
useEffect(() => {console.log(questionsArray)}, [questionsArray]);
// Returning html markup here
return (<>
<div className = 'questions-container'>
{/* {questionsArray.map(questionObject => <h1>{questionObject.question}</h1>)} */}
<h1>{questionsArray[0].question}</h1>
</div>
</>)
}
export default PlayQuiz;(顺便说一句,这段代码包含的所有控制台日志只是为了让我可视化到底发生了什么)
在下面的代码中,我使用axios从API获取数据,然后在我的questionsArray中解析数据。然后,我想打印一个标题标签到我的dom中,它包含数组中的第一个元素,即对象,并获取该对象的问题属性,其中包含实际的问题。但是当我这样做的时候:<h1>{questionsArray[0].questions}</h1>,它抛出一个错误,说无法读取未定义的属性问题。
以防万一,如果你们中的任何人想要查看我从API获得的对象:

在这个对象中,我从对象中的数据键获得results对象值,并将其设置为questionsArray。
如果你们中的任何人想看看我的questionsArray中存储了什么:

如何修复此错误?
发布于 2020-09-28 18:00:58
您可以尝试可选的链接?.
<h1>{questionsArray[0]?.question}</h1>看看这个:https://codesandbox.io/s/strange-lovelace-06u3x?file=/src/App.js
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
发布于 2020-09-28 17:55:43
当React呈现您的数据时,axios没有完全获取您的数据,并且您的questionsArray未定义或为空。只需检查axios是否已完成数据获取。
return (<>
<div className = 'questions-container'>
{/* {questionsArray && questionsArray.map(questionObject => <h1>{questionObject.question}</h1>)} */}
<h1>{questionsArray[0].question}</h1>
</div>
</>)
这将确保您的数据已定义或不为空
https://stackoverflow.com/questions/64099713
复制相似问题