无法访问处于 ReactJS 状态的数组索引



我从一个琐事应用程序中获得了一些信息,并分别设置了我的状态。

componentDidMount(){
axios.get('https://opentdb.com/api.php?amount=50').then( response =>{
for(var key in response.data.results){
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]
}));    
}
});
}

注意:questions是一个字符串,answer也是,然而,wrongAnswers是一个数组。

每当我试图在jsx代码中呈现错误答案时,数据都会按原样显示。然而,每当我试图访问索引或映射数组的元素时,我都会收到一个错误,说它是未定义的。我认为这可能与我在componentDidmount中同步数据有关,所以我检查了render方法,看看显示了什么。

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

第一次渲染时我没有定义,但从那时起,每次UI更新时,我都会显示正确的数组,如果我把它放在jsx代码中,数组也会像它应该显示的那样显示。

然而,我想将错误答案映射到类似的单选按钮

{this.state.wrongAnswers[this.state.random].map((wrongAnswer, index) => {
<p key={'Key-'+index}>{wrongAnswer}</p>
})}
<form action="">
<input type="radio" name="gender" value={wrongAnswer} /> 
Male<br/>
<input type="radio" name="gender" value={wrongAnswer}/> 
Female<br/>
<input type="radio" name="gender" value={wrongAnswer}/> 
Other<br/>
</form>

首先,我建议您先进行状态合并,然后调用setState((一次。想象一下,如果你的数量=50,那么在显示最终结果之前,你的应用程序会自我更新50次。

第二个建议是,在渲染来自您所在州的数据之前,先设置一个条件,以确保在渲染时您所在州列表没有未定义。

class Component React.Component {
state= {
random: someValue,
questions: [],
answers: [],
wrongAnswers: []
}
componentDidMount() {
// Your api logic
// merge and prepare new state object before calling this.setState() !!
const newObject = mergeLogic();
// then setState to execute update just once
this.setState({wrongAnswers: newObject})
}
render() {
const {random, wrongAnswers } = this.state;
return (
{wrongAnswers && wrongAnswers[random].map((wrongAnswer, index) => {
<p key={'Key-'+index}>{wrongAnswer}</p>
})}
// your other code...
);
}
}

最新更新