[英]Access nested array items in javascript
我正在使用javascript trivia API制作應用程序。 我在顯示錯誤答案的每個值時遇到問題。
到目前為止,我已經將它們以及問題和正確答案保存在我的狀態中
componentDidMount() {
axios.get('https://opentdb.com/api.php?amount=50').then(response => {
for (var key in response.data.results) {
console.log(response.data.results[key].question)
this.setState(prevState => ({
questions: [...prevState.questions, response.data.results[key].question],
answers: [...prevState.answers, response.data.results[key].correct_answer],
wrongAnswers: [...prevState.wrongAnswers, response.data.results[key].incorrect_answers]
}));
}
});
}
這很好用,但是我的問題是錯誤的答案是數組本身,所以每當我顯示狀態時
<p>{this.state.wrongAnswers[this.state.random]}</p> // prints array of strings
我得到另一個數組,我可以使用點運算符訪問每個元素,因為由於問題是隨機選擇的,所以我不知道答案。
我想使用單選按鈕動態顯示值。 有沒有辦法訪問嵌套數組的每個元素並動態顯示它們?
您可以遍歷該數組並顯示錯誤的答案
{Array.isArray(this.state.wrongAnswers) && this.state.wrongAnswers.map((wrongAnswer, index) => {
<p key={'Key-'+index}>wrongAnswer}</p>
}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.