React.js-无法访问对象数组内的值
2020-09-14
349
我一直试图访问对象数组内的值,但是由于某种原因,当我使用
console.log(quiz.questions[0].question)
时,我收到错误
TypeError: Cannot read property 'question' of undefined
代码:
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
3个回答
通常,这意味着您正在尝试访问可能为
null
或
undefined
的变量的属性。
可能您需要首先更改初始
useState
,因为
questions
是一个数组,而不是对象
{}code>,如下所示:
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);
norbitrial
2020-09-14
为了正确访问测验字段值,建议使用另一个 useEffect 来监视
quiz
状态:
useEffect(() => {
if(quiz.questions.length){
console.log(quiz.questions[0].question);
}
}, [quiz]);
Boussadjra Brahim
2020-09-14
看起来你正在尝试将对象 {} 用作数组 []!
Javascript 试图访问的是:
{
"0" : { // your data},
}
它看起来应该是这样的:
[
0 : { // your data},
]
你想要改变的是:
const [quiz, setQuiz] = useState({
title: '',
questions: [], // make it an array
});
并且可能考虑使用 .push() 将单个对象推送到数组
Axel Rothe
2020-09-14