首页 > 解决方案 > 我尝试映射我映射但无法到达的数组的内容(未定义为 no-undef)

问题描述

在我的实现中,我想从我的 JSON 数据库中加载一系列问题,以进行测验。我的函数加载问题并映射它们。现在在检查是否还有未解决的问题(在分数选择中显示分数?)后,它应该获取问题数组并映射答案选项。我的问题是,我无法回答问题(“问题”未定义为 no-undef),因为我要求介于两者之间的 showcore。有没有办法编译它?

我的代码如下所示:(数据库现在只是填充问题)

import './play_quiz.css';
import React from "react"

class Play_quiz extends React.Component {

    state = {
        currentQuestion: 0,
        showScore: false,
        score: 0,
        questions: []
    }

    componentDidMount() {
        this.getRandomizedQuestions();
        console.log("Current state:")
    }

    getRandomizedQuestions = () => {
        const apiUrl = 'http://localhost:3001/questions'
        fetch(apiUrl)
            .then((response) => response.json())
            .then(
                (result) => {
                    console.log("From database:");
                    console.log(result);

                    let amountOfQuestions = result.length;
                    let randomizedResult = [];
                    for (let i = 0; i < amountOfQuestions; i++) {
                       let randomIndex = Math.floor(Math.random() * result.length);
                       randomizedResult.push(result[randomIndex]);
                       result.splice(randomIndex, 1);
                    }
                    //const randomizedResult  = result.sort(() => Math.random() - 0.5)
                    this.setState({questions: randomizedResult });
                },
                (error) => {
                    console.log('An unexpected error occurred', error);
                }
            );
    };


    handleAnswerOptionClick = (isCorrect) => {
        if (isCorrect) {
            this.setState({ score: this.state.score + 1 });
        }

        const nextQuestion = this.state.currentQuestion + 1;
        if (nextQuestion < this.state.questions.length) {
            this.setState({
                currentQuestion: nextQuestion
            })
        } else {
            this.setState({
                showScore: true
            })
        }
    };

    updateCurrentQuestion = () => {
        this.setState({ currentQuestion: this.state.currentQuestion + 1 })

    }

    render() {
        return (
            <div className='quiz-window'>
                {this.state.questions.map((question, index) => (
                    <div key={index}>
                        {question.title}
                    </div>)
                )
                }
                {this.state.showScore ? (
                    <div className='score-section'>
                        korrekt beantwortet: {this.state.score} von {this.state.questions.length}
                    </div>
                ) : (
                        <div>
                            <div className='question-section'>
                                <div className='question-count'>
                                    <span>Frage {this.updateCurrentQuestion}</span>/{this.state.questions.length}
                                </div>
                            </div>

                            <div className='answer-section'>
                                {question.answers.map(answer => (
                                                  <button key={answer.number} onClick={() => this.handleAnswerOptionClick(answer.isCorrect)}>
                                                  {answer.answer}
                                                  </button>
                                    ))}
                            </div>
                        </div>
                    )
                }
            </div>
        )
    }
}
export default Play_quiz;
{
  "questions": [
    {
      "id": 0,
      "title": "Pi Dezimal",
      "author": "Timo",
      "isMC": false,
      "question": "Wie lauten die 4 ersten Dezimalstellen von Pi?",
      "answers": "1415",
      "category": null
    },
    {
      "id": 1,
      "title": "Längster Fluss",
      "author": "Timo",
      "isMC": true,
      "question": "Welcher ist der längte Fluss der Welt?",
      "answers": [
        {
          "number": 1,
          "answer": "Donau",
          "isCorrect": false
        },
        {
          "number": 2,
          "answer": "Nil",
          "isCorrect": true
        },
        {
          "number": 3,
          "answer": "Wolga",
          "isCorrect": false
        },
        {
          "number": 4,
          "answer": "Amazonas",
          "isCorrect": false
        }
      ],
      "category": null
    },
    {
      "id": 2,
      "title": "Energieaufnahme Pflanzen",
      "author": "Timo",
      "isMC": false,
      "question": "Durch welchen Vorgang gewinnen Pflanzen Energie?",
      "answers": "Photosynthese",
      "category": null
    }
  ],


  "quizzes": [
    {
      "id": 0,
      "player": "Emil",
      "questions" : [
        {
          "number" : 0,
          "referenceID" : 1,
          "isAnswered" : false,
          "isCorrectlyAnswered" : false
        },
        {
          "number" : 1,
          "referenceID" : 0,
          "isAnswered" : false,
          "isCorrectlyAnswered" : false
        }
      ],
      "grade" : null,
      "editingTime" : null,
      "isFinished" : false
    }
  ],


  "profile": {
    "name": "typicode"
  }
}

标签: javascriptjsonreactjsmap-function

解决方案


我不知道您是否想要question.answers.map内部this.state.questions.map并忘记为此关闭 {},但基本上您question没有在没有映射到您的questions数组的情况下定义

尝试改变这个:

{question.answers.map(answer => (
    <button key={answer.number} onClick={() => this.handleAnswerOptionClick(answer.isCorrect)}>
    answer.answer
    </button>
))}

对此:

              {this.state.questions.map((question) => {
                return (
                  <>
                    {question.answers.map(answer => 
                      <button
                        key={answer.number}
                        onClick={() => this.handleAnswerOptionClick(answer.isCorrect)}>
                        {answer.answer}
                      </button>
                    )}
                  </>
                );
              })}

推荐阅读