【问题标题】:TypeError: Cannot read property 'map' of undefined in passing jsonfile to a cponentTypeError:在将 json 文件传递​​给组件时无法读取未定义的属性“映射”
【发布时间】:2020-12-31 11:46:34
【问题描述】:

我正在尝试读取 JSON 文件并尝试将其传递给组件,但是我收到此错误,TypeError: Cannot read property 'map' of undefined 而且我似乎找不到问题所在。

这是我创建的代码:

export default function Questions() {

    const [currentQuestion, setCurrentQuestion] = useState(0);
    const [showScore, setShowScore] = useState(false);
    const [score, setScore] = useState(0);
    const quizQuestions = quiz.questions;

    const handleAnswerOptionClick = (isCorrect) => {
        if (isCorrect) {
            setScore(score + 1);
        }

        const nextQuestion = currentQuestion + 1;
        if (nextQuestion < quizQuestions.length) {
            setCurrentQuestion(nextQuestion);
        } else {
            setShowScore(true);
        }
    };
    
    quizQuestions.map((quizQuestions)=> {
    return (
        <div className='questions'>
      

            <div className="questions_row">
                {showScore ? (
                    <div className='score-section'>
                        You scored {score} out of {quizQuestions.length}
                    </div>
                ) : (
                        <>
                            <QuestionsProduct
                                title="Introduction to Programming2"
                                questioNum={currentQuestion + 1}
                                question={quizQuestions[currentQuestion].quizQuestions.questionText}
                                answers={quizQuestions[currentQuestion].quizQuestions.answerOptions.map((answerOption) => (
                                    <label onClick={() => handleAnswerOptionClick(quizQuestions.answerOption.isCorrect)}
                                        type="checkbox">{answerOption.quizQuestions.answerText}</label>
                                ))}
                            />
                        </>
                                   
                    )}
            </div> 
        </div>);
    })
}

json 文件名为 quiz.json。我目前在内部拥有这些数据,但是我想创建更多问题,因此 json 文件将是理想的。这是创建的json文件

[{ "questions" : {
        "questionText": "What is the capital of France?",
        "answerOptions": [
            { "answerText": "New York", "isCorrect": false },
            { "answerText": "London", "isCorrect": false },
            { "answerText": "Paris", "isCorrect": true },
            { "answerText": "Dublin", "isCorrect": false }
        ]
    },
    
        "questionText2": "What is the capital of France 2?",
        "answerOptions": [
            { "answerText": "New York", "isCorrect": false },
            { "answerText": "London", "isCorrect": false },
            { "answerText": "Paris", "isCorrect": true },
            { "answerText": "Dublin", "isCorrect": false }
        ]
     }
]

【问题讨论】:

  • quizQuestions 有要映射的数据吗?请添加更多代码以及从哪里获取问题数据
  • 是的,它从 jason 文件中读取。这是整个代码:

标签: reactjs dictionary undefined


【解决方案1】:

尝试进行空检查

quizQuestions && quizQuestions.map((quizQuestion)=> { return ()}

也不要在地图内使用相同的quizQuestions

【讨论】:

    【解决方案2】:

    出现此错误是因为 quizQuestions 具有空值

    【讨论】:

      【解决方案3】:

      假设您有一个从 Json 获取数据的函数,如下所示:

        const [quizQuestions, setQuizQuestions]=useState([]);
        const getQuestionData=()=>{
          fetch('data.json'
          ,{
            headers : { 
              'Content-Type': 'application/json',
              'Accept': 'application/json'
             }
          }
          )
            .then(function(response){
              console.log(response)
              return response.json();
            })
            .then(function(myJson) {
              console.log(myJson);
              setQuizQuestions(myJson)
            });
        }
      

      然后从useEffect调用这个函数:

        useEffect(()=>{
          getQuestionData()
        },[])
      

      然后渲染数据如下:

        return (
          <div className="App">
           {
             quizQuestions && quizQuestions.length>0 && 
                quizQuestions.map((item)=>
                    <p>{item.title}</p>
                )
           }
          </div>
        );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-11
        • 2022-06-21
        • 2021-04-09
        • 1970-01-01
        • 2021-06-20
        • 1970-01-01
        • 2021-08-05
        • 1970-01-01
        相关资源
        最近更新 更多