首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法读取未定义的属性“questions”

无法读取未定义的属性“questions”
EN

Stack Overflow用户
提问于 2020-09-28 17:43:56
回答 2查看 528关注 0票数 0

在这个应用程序中,我尝试创建一个测验应用程序。

代码语言:javascript
复制
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中存储了什么:

如何修复此错误?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-09-28 18:00:58

您可以尝试可选的链接?.

代码语言:javascript
复制
<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

票数 1
EN

Stack Overflow用户

发布于 2020-09-28 17:55:43

当React呈现您的数据时,axios没有完全获取您的数据,并且您的questionsArray未定义或为空。只需检查axios是否已完成数据获取。

代码语言:javascript
复制
return (<>
    <div className = 'questions-container'>
        {/* {questionsArray && questionsArray.map(questionObject => <h1>{questionObject.question}</h1>)} */}
<h1>{questionsArray[0].question}</h1>
    </div>
</>)

这将确保您的数据已定义或不为空

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64099713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档