【问题标题】:Creating an array from dynamically updating arrays从动态更新数组创建数组
【发布时间】: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


    【解决方案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 和 wrongAnswers 元素的数组。

    希望这会有所帮助。

    【讨论】:

    • 我试过了,当我尝试通过它进行映射时,它给出了一个错误,说 this.state.allAnswers[this.state.random].map 不是一个函数
    • 问题是答案是一个字符串,这将导致连接到字符串
    猜你喜欢
    • 2018-01-23
    • 2017-09-08
    • 1970-01-01
    • 2018-09-26
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    相关资源
    最近更新 更多