【发布时间】:2019-05-10 05:10:38
【问题描述】:
我的 React 项目中有一个琐事应用程序,我从 api 获取一些数据:
问题 错误的回答者 正确答案
现在我想对正确答案中的错误进行一个数组并将它们映射,以便用户以随机顺序获得所有可能的答案。
我在创建“allAnswers”数组时遇到问题
componentDidMount(){
axios.get('https://opentdb.com/api.php?amount=50').then( response =>{
for(var key in response.data.results){
const question = [...this.state.question, response.data.results[key].question]; // here i put the data into state in each category
const answer = [...this.state.answer, response.data.results[key].correct_answer];
const wrongAnswers = [...this.state.wrongAnswers, response.data.results[key].incorrect_answers];
const allAnswers = [wrongAnswers, answer] // here im trying to collec all possible answers and then later make a handler to check if the given answer was right or wrong
this.setState( prevState => ({
question: question,
answer: answer,
wrongAnswers: wrongAnswers,
allAnswers: allAnswers,
}));
}
});
}so i save 50 questions and respective answers and wrong answers to not send net work requests all the time.
Then i have made a random counter, that i use to map a random question
<p>{this.state.question[this.state.random]}</p>
i then map through the array of all the answers to get each answer displayed
{this.state.random !== undefined && this.state.wrongAnswers[this.state.random] !== undefined && this.state.allAnswers[this.state.random].map((answer, index) => {
console.log(this.state.allAnswers[this.state.random])
return(
<form >
<input type="radio" name="name" value="!!" /> {answer}<br/>
</form>
)
})
})
我的问题是 allAnswers 数组只是错误的答案,我无法找到一种方法来在州内以各自的方式收集所有正确和错误的答案。
【问题讨论】:
标签: javascript arrays reactjs api fetch