React 应用程序使用 json 服务器,无法从服务器呈现数据
2022-02-13
246
我尝试使用 useEffect 从 json 服务器获取一些数据,但出现以下错误:Uncaught TypeError:无法读取未定义的属性(读取“questionText”)。在使用 json 服务器复制数据库之前,我能够显示数据。如能得到任何帮助,我将不胜感激。提前致谢。
import {useState, useEffect} from 'react';
const QuestionSection = () => {
const [questions, setQuestions] = useState([]);
const [currentQuestion, setCurrentQuestion] = useState(0);
const [showScore, setShowScore] = useState(false);
const [score, setScore] = useState(0);
useEffect(() => {
const getQuestions = async () => {
const questionsFromServer = await fetchQuestions()
setQuestions(questionsFromServer)
}
getQuestions()
}, [])
//Fetch questions
const fetchQuestions = async () => {
const res = await fetch ('http://localhost:5000/questions');
const data = await res.json();
return data
}
const handleAnswerOptionClick = (correct) => {
if (correct) {
setScore(score + 1);
}
const nextQuestion = currentQuestion + 1;
if (nextQuestion < questions.length) {
setCurrentQuestion(nextQuestion);
} else {
setShowScore(true);
}
};
return (
<questionSection>
<div className='questionSection'>
{showScore ? (
<div className='score-section'>
You scored {score} out of {questions.length}
</div>
) : (
<>
<div className='question-section'>
<div className='question-count'>
<span>Question {currentQuestion + 1}</span>/{questions.length}
</div>
<div className='question-text'>{questions[currentQuestion].questionText}</div>
</div>
<div className='answer-section'>
{questions[currentQuestion].answerOptions.map((answerOption) => (
<button key = {answerOption.id} onClick={() => handleAnswerOptionClick(answerOption.correct)}>{answerOption.answerLetter} {answerOption.answerText}</button>
))}
</div>
</>
)}
</div>
</questionSection>
)
}
export default QuestionSection
2个回答
由于获取问题是一个异步操作,因此您必须在代码中处理未定义的情况。
一个简单的解决方法是在 questionText 属性之前添加
?
:
<div className='question-text'>{questions[currentQuestion]?.questionText}</div>
问号检查
currentQuestion
是否存在于问题数组中,如果存在,则显示
questionText
。
Kostas Panagiotakis
2022-02-13
最初数组为空,执行 `` 将返回
undefined
。错误信息就是这样。这种情况将一直发生,直到 API 调用完成并解决。
您可以根据自己的偏好显示不同的 UI。例如,以下代码显示
Fetching questions
一段时间:
<questionSection>
<div className='questionSection'>
{showScore ? (
<div className='score-section'>
You scored {score} out of {questions.length}
</div>
) : (
questions.length > 0 ? <>
<div className='question-section'>
<div className='question-count'>
<span>Question {currentQuestion + 1}</span>/{questions.length}
</div>
<div className='question-text'>{questions[currentQuestion].questionText}</div>
</div>
<div className='answer-section'>
{questions[currentQuestion].answerOptions.map((answerOption) => (
<button key = {answerOption.id} onClick={() => handleAnswerOptionClick(answerOption.correct)}>{answerOption.answerLetter} {answerOption.answerText}</button>
))}
</div>
</> : <p>Fetching Questions</p>
)}
</div>
</questionSection>
Tushar Shahi
2022-02-15