我一直在尝试访问对象数组中的值,但是由于某些原因,当我使用console.log(quiz.questions[0].question)
时出现错误
TypeError:无法读取未定义的属性“问题”
代码:
const quizAPI = process.env.REACT_APP_API_QUIZ;
const PlayQuiz = () => {
const [quiz, setQuiz] = useState({
title: '',
questions: {},
});
useEffect(() => {
async function getQuiz() {
const param = window.location.search;
const id = param.split('=');
const Quiz = await axios.get(`${quizAPI}?_id=${id[1]}`);
const { doc } = Quiz.data.data;
console.log(doc[0]);
const quizDoc = doc[0];
setQuiz({ ...quiz, title: quizDoc.title, questions: quizDoc.questions });
}
getQuiz();
}, []);
console.log(quiz.questions[0].question);
console.log(quiz)
显示的内容:
{title: "findme", questions: Array(3)}
questions: Array(3)
0: {_id: "5f5500caab44c4bd2b58b109", question: "sfdf", answerSelectionOne: "sdvsv", answerSelectionTwo: "asd", answerSelectionThree: "", …}
1: {_id: "5f5500cdab44c4bd2b58b10a", question: "sfdfddd", answerSelectionOne: "sdvsv", answerSelectionTwo: "asd", answerSelectionThree: "", …}
2: {_id: "5f5500cfab44c4bd2b58b10b", question: "sfdfdddv", answerSelectionOne: "sdvsv", answerSelectionTwo: "asd", answerSelectionThree: "", …}
length: 3
__proto__: Array(0)
title: "findme"
__proto__: Object
答案 0 :(得分:2)
通常,这意味着您试图访问可能是null
或undefined
变量的属性。
可能首先需要更改初始的useState
,因为questions
是一个数组,而不是对象{}
,如下所示:
const [quiz, setQuiz] = useState({
title: '',
questions: [],
});
第二quiz.questions
可以有length
个0
。因此,通过像quiz.questions.length > 0
这样的简单检查,就可以消除该问题。
然后您可以将日志记录用作:
console.log(quiz.questions.length > 0 ? quiz.questions[0].question : null);
答案 1 :(得分:1)
为了正确访问测验字段值,建议使用另一个监视quiz
状态的useEffect:
useEffect(() => {
if(quiz.questions.length){
console.log(quiz.questions[0].question);
}
}, [quiz]);
答案 2 :(得分:1)
似乎您正在尝试将对象{}用作数组[]!
Javascript试图做的是访问此文件:
{
"0" : { // your data},
}
应该是什么样子
[
0 : { // your data},
]
您要更改的是:
const [quiz, setQuiz] = useState({
title: '',
questions: [], // make it an array
});
并可能考虑使用.push()将单个对象推入数组