I don't know if my code is correct or not, but it gives this error:
TypeError: this.state.questions.map is not a function.
Why am I encountering this behavior?
import React from "react";
import axios from "axios";
import Countdown from "react-countdown-now";
class QuizApp extends React.Component {
constructor(props) {
super(props);
this.state = {
questions: [],
ch: []
};
}
componentDidMount() {
axios.get("http://private-anon-c06008d89c-quizmasters.apiary-mock.com/questions")
.then(response => {
const { questions, ch } = response.data;
this.setState({ questions, ch });
});
}
render() {
<div>
<ul>
{this.state.questions.map((que, index) => {
<li>{que.questions} </li>;
{
this.ch[index].map(choice => <li>{choice}</li>);
}
})}
</ul>
</div>;
}
}
Upon looking at the network call response, I could see that response.data is of type array. But as you are applying object destructuring to obtain questions, it gets the value undefined. Hence the map at render fails as this.state.questions is undefined.
import React from 'react';
import axios from 'axios';
import Countdown from 'react-countdown-now';
class QuizApp extends React.Component {
constructor(props) {
super(props);
this.state = {
questions: [],
ch: [],
};
}
componentDidMount() {
axios
.get('http://private-anon-c06008d89c-quizmasters.apiary-mock.com/questions')
.then((response) => {
const allQuestions = [];
const allChoices = [];
response.data.forEach(([{question, choices}]) => {
allQuestions.push(question);
allChoices.push(choices)
})
this.setState({ questions: allQuestions, ch: allChoices});
});
}
render() {
<div>
<ul>
{this.state.questions.map((que, index) => {
<li>{que.questions} </li>;
{
this.ch[index].map((choice) => <li>{choice}</li>);
}
})}
</ul>
</div>;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.