在componentDidMount

时间:2018-12-02 11:19:23

标签: reactjs asynchronous get axios

我有一个react组件,我想在其中获取一些数据,使用componentDidmount最初获取数据:

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];
    const answer = [...this.state.answer, response.data.results[key].correct_answer];
    const wrongAnswers = [...this.state.wrongAnswers, response.data.results[key].incorrect_answers];
    this.setState( prevState => ({
        question: question,
        answer: answer,
        wrongAnswers: wrongAnswers
 }));    
 }
  });
 }

问题是我无法映射出错误答案的答案,因为它们最初是不确定的

  const {wrongAnswers} = this.state;
 {wrongAnswers[this.state.random] && this.state.wrongAnswers[this.state.random].map((wrongAnswer, index) => { //this does not display 
<p key={'Key-'+index}>here it is= {wrongAnswer}</p>
  })}

我尝试进行一些检查以查看何时呈现什么内容

 {this.state.wrongAnswers &&
console.log('the state is ' +this.state.wrongAnswers[this.state.random]);
} //this renders undefined initially, then renders an array of the right answers..

奇怪的是,如果我仅显示状态而不执行任何操作,则显示正确。

  <p>{this.state.question[this.state.random]}</p> // displays the state correctly

  <p>{this.state.wrongAnswers[this.state.random]}</p> //displays the state correctly

我怀疑我无法执行任何操作,因为它最初并未加载,但是由于我将其放在componentDidMount中,您会怀疑不会发生此问题?

编辑:

只要我为简单的parapragh设置条件

{this.state.random !== undefined && this.state.wrongAnswers[this.state.random] !== undefined &&

    <p> condition is met </p>

  }

它打印出来

但是当我映射数组时:

  {this.state.random !== undefined && this.state.wrongAnswers[this.state.random] !== undefined && this.state.wrongAnswers[this.state.random].map((wrongAnswer, index) => {
      console.log('inside the right method!'); //logs correctly three times like intended but does not print any jsx
    <p key={'Key-'+index}>here it is= {wrongAnswer}</p>

  })}

什么都没有打印出来。

1 个答案:

答案 0 :(得分:1)

您说过<p>{this.state.wrongAnswers[this.state.random]}</p>放在渲染钩子中时有效。这意味着您将始终得到wrongAnswers即。不是undefined并调用状态的wrongAnswers数组,则在初始渲染时不会出错,并且在下一次渲染时会获得正确的结果。

但是在componentDidMount挂钩中使用此代码,

{
  this.state.wrongAnswers &&
  console.log(this.state.wrongAnswers[this.state.random]);
}

第一次,它显然会得到undefined,因为那时this.state.random可能是undefinednull,由于这个原因,您会得到{{ 1}}。例如:

undefined

因此,我建议您先检查const arr = [1,2,3] console.log(arr[undefined]) // undefined console.log(arr[null]) // undefined状态,然后再使用random

wrongAnswers

由于您在初始状态下{ this.state.random && console.log(this.state.wrongAnswers[this.state.random]); } 并非wrongAnswers,因此以下内容是不必要的。如果您尚未将undefined设置为初始状态,那么只有以下一种方法可以实现:

wrongAnswers

对不起,在您进行编辑之前我没有弄清楚。但是,由于要使用花括号,因此您需要在地图内使用return语句:

{
  this.state.wrongAnswers &&
  this.state.random &&
  console.log(this.state.wrongAnswers[this.state.random]);
}

您可能还想向in this post寻求进一步的帮助,以了解何时使用return以及何时不使用return。