Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - Error trying to render an array of objects from the database

I'm trying to load an Array of Questions for a Quiz App, but in the method which collects the questions from the JSON database, the following warning error occurs:

Error: Objects are not valid as a React child (found: object with keys {number, answer, isCorrect}). If you meant to render a collection of children, use an array instead.

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);
            }
            this.setState({questions: randomizedResult });

            }, (error) => {
                console.log('An unexpected error occurred', error);
            });
}; 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are returning an object of answer {number, answer, isCorrect} you should just map into answer after mapping into question:

render() {
  // add logic and constant here
  return (
    //... add another component or jsx
    <div className='show-score'>{showScore}</div>
    <div className='quiz-window'>
      {this.state.questions.map((question, index) => (
        <div key={index}>
          {question.title}
          <div className='answer-section'>
            {question.answers.map(answer => (
              <button key={answer.number} onClick={() => this.handleAnswerOptionClick(answer.isCorrect)}>
                {answer.answer}
              </button>
            ))}
          </div>
        </div>
      ))}
    </div>
    //... add another component or jsx
  )
}

Bonus: For randomizing items inside array Instead of:

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

Use this code:

const randomizedResult  = result.sort(() => Math.random() - 0.5)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...