Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...