简体   繁体   English

React.js - 无法访问对象数组中的值

[英]React.js - Unable to access values inside array of objects

I've been trying to access the values inside an array of objects but for some reason when I use console.log(quiz.questions[0].question) I get the error我一直在尝试访问对象数组中的值,但是由于某种原因,当我使用console.log(quiz.questions[0].question)出现错误

TypeError: Cannot read property 'question' of undefined类型错误:无法读取未定义的属性“问题”

code:代码:

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);

what console.log(quiz) shows:什么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

Usually this means you are trying to access a property on a possibly null or undefined variable.通常这意味着您正在尝试访问可能为nullundefined变量的属性。

Probably you need to change the initial useState first because questions is an array and not an object {} as the following:可能您需要先更改初始useState因为questions是一个数组而不是对象{} ,如下所示:

const [quiz, setQuiz] = useState({
    title: '',
    questions: [],
});

Secondly quiz.questions can have length of 0 .其次quiz.questions length可以为0 So with a simple check before like quiz.questions.length > 0 you can eliminate that issue.因此,通过像quiz.questions.length > 0这样的简单检查,您可以消除该问题。

Then you can use logging as:然后您可以将日志记录用作:

console.log(quiz.questions.length > 0 ? quiz.questions[0].question : null);

In order to access the quiz field values correctly it is recommended to use another useEffect that watches the quiz state :为了正确访问测验字段值,建议使用另一个监视quiz状态的 useEffect :

    useEffect(() => {
        
        if(quiz.questions.length){
           console.log(quiz.questions[0].question);
         }
        
    }, [quiz]);

it seems like you are trying to use an object {} as an array []!似乎您正在尝试将对象 {} 用作数组 []!

What Javascript is trying to do is access this: Javascript 试图做的是访问这个:

{
 "0" : { // your data},
}

What it should look like:它应该是什么样子:

[
 0 : { // your data},
]

What you want to change is :你想改变的是:

const [quiz, setQuiz] = useState({
    title: '',
    questions: [], // make it an array
});

And possibly consider using .push() to push individual objects to an array并可能考虑使用 .push() 将单个对象推送到数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM