我的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数组只是错误的答案,我找不到在州内以各自的方式收集所有正确答案和错误答案的方法。
答案 0 :(得分:1)
您可以使用传播运算符来合并两个数组。
const answer = [...this.state.answer, response.data.results[key].correct_answer];
const wrongAnswers = [...this.state.wrongAnswers, response.data.results[key].incorrect_answers];
const allAnswers = [...answer, ...wrongAnswers];
这将导致一个数组,其中包含answer和rongAnswers的元素。
希望这会有所帮助。