我的 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,
}));
}
});
}
所以我保存了 50 个问题以及各自的答案和错误答案,以免一直发送网络请求。
然后我制作了一个随机计数器,用于映射随机问题:
<p>{this.state.question[this.state.random]}</p>
然后,我映射所有答案的数组以显示每个答案:
{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
数组只是错误的答案,我找不到一种方法来在状态内以各自的方式收集所有正确和错误的答案。
最佳答案
您可以使用扩展运算符来连接两个数组。
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];
这将产生一个包含答案和错误答案元素的数组。
希望这有帮助。
关于javascript - 从动态更新数组创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53686398/