最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

TypeError:无法在 MERN Stack Quiz App 上读取未定义的属性(读取“地图”)

网站源码admin45浏览0评论

TypeError:无法在 MERN Stack Quiz App 上读取未定义的属性(读取“地图”)

TypeError:无法在 MERN Stack Quiz App 上读取未定义的属性(读取“地图”)

大家好,

我正在尝试使用 MERN 堆栈构建一个测验应用程序。 尽管一切正常,但无法访问问题列表,因为它会抛出类型错误:无法读取未定义的属性(读取“地图”)。

我目前在两个组件 JavaScript 文件中使用 map() 函数:Questions.js 和 ResultTable.js。

如果你能指导我,那将是很大的帮助。

提前致谢! :)

问题.JS

import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'


/** Custom Hook */
import { useFetchQestion } from '../hooks/FetchQuestion'
import { updateResult } from '../hooks/setResult'


export default function Questions({ onChecked }) {

    const [checked, setChecked] = useState(undefined)
    const { trace } = useSelector(state => state.questions);
    const result = useSelector(state => state.result.result);
    const [{ isLoading, apiData, serverError}] = useFetchQestion() 

    const questions = useSelector(state => state.questions.queue[state.questions.trace])
    const dispatch = useDispatch()

    useEffect(() => {
        dispatch(updateResult({ trace, checked}))
    }, [checked])
    
    function onSelect(i){
        onChecked(i)
        setChecked(i)
        dispatch(updateResult({ trace, checked}))
    }


    if(isLoading) return <h3 className='text-light'>isLoading</h3>
    if(serverError) return <h3 className='text-light'>{serverError || "Unknown Error"}</h3>

  return (
    <div className='questions'>
        <h2 className='text-light'>{questions?.question}</h2>

        <ul key={questions?.id}>
            {
                questions?.options.map((q, i) => (
                    <li key={i}>
                        <input 
                            type="radio"
                            value={false}
                            name="options"
                            id={`q${i}-option`}
                            onChange={() => onSelect(i)}
                        />

                        <label className='text-primary' htmlFor={`q${i}-option`}>{q}</label>
                        <div className={`check ${result[trace] == i ? 'checked' : ''}`}></div>
                    </li>
                ))
            }
        </ul>
    </div>
  )
}

RESULT_TABLE.JS

import React, { useEffect, useState } from 'react'
import { getServerData } from '../helper/helper'

export default function ResultTable() {

    const [data, setData] = useState([])

    useEffect(() => {
        getServerData(`${process.env.REACT_APP_SERVER_HOSTNAME}/api/result`, (res) => {
            setData(res)
        })
    })

  return (
    <div>
        <table>
            <thead className='table-header'>
                <tr className='table-row'>
                    <td>Name</td>
                    <td>Attemps</td>
                    <td>Earn Points</td>
                    <td>Result</td>
                </tr>
            </thead>
            <tbody>
                { !data ?? <div>No Data Found </div>}
                {
                    data.map((v, i) => (
                        <tr className='table-body' key={i}>
                            <td>{v?.username || ''}</td>
                            <td>{v?.attempts || 0}</td>
                            <td>{v?.points || 0}</td>
                            <td>{v?.achived || ""}</td>
                        </tr>
                    ))
                }
                
            </tbody>
        </table>
    </div>
  )
}

回答如下:

在未定义或空的对象上调用 map() 函数时,会出现错误“TypeError: Cannot read properties of undefined (reading 'map')”。在您的情况下,错误来自 Questions.js 和 ResultTable.js 文件,分别尝试访问选项和数据对象上的“map”方法。

在 Questions.js 文件中,questions 对象被定义为 state.questions.queue[state.questions.trace],如果状态设置不当,它可能是未定义的。因此,您应该在访问选项对象之前添加一个空检查,如下所示:

{
    questions?.options && questions?.options.map((q, i) => (
        <li key={i}>
            <input 
                type="radio"
                value={false}
                name="options"
                id={`q${i}-option`}
                onChange={() => onSelect(i)}
            />

            <label className='text-primary' htmlFor={`q${i}-option`}>{q}</label>
            <div className={`check ${result[trace] == i ? 'checked' : ''}`}></div>
        </li>
    ))
}

同样,在ResultTable.js文件中,你也应该在访问它的map()方法之前检查数据对象是否被定义。您可以修改代码如下所示:

{data && data.map((v, i) => (
    <tr className='table-body' key={i}>
        <td>{v?.username || ''}</td>
        <td>{v?.attempts || 0}</td>
        <td>{v?.points || 0}</td>
        <td>{v?.achived || ""}</td>
    </tr>
))}

通过添加这些空检查,您可以避免代码中的 TypeError: Cannot read properties of undefined (reading 'map') 错误。

发布评论

评论列表(0)

  1. 暂无评论