Javascript can';t处于ReactJS状态的数组的访问索引
我正在从一个琐事应用程序中获取一些信息,并分别设置我的状态Javascript can';t处于ReactJS状态的数组的访问索引,javascript,reactjs,Javascript,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
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]
}));
}
});
}
注意:问题是字符串,答案也是字符串,但是错误答案是数组
每当我试图在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>
{this.state.ErrorAnswers[this.state.random].map((ErrorAnswer,index)=>{
{errowresponse}
})}
男性
女性
其他
首先,我建议您先合并状态,然后调用setState()。想象一下,如果你的amount=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...
);
}
}
类组件React.Component{
状态={
random:someValue,
问题:[],
答复:[],
错误答案:[]
}
componentDidMount(){
//您的api逻辑
//在调用此.setState()之前,合并并准备新的状态对象!!
const newObject=mergeLogic();
//然后将state设置为只执行一次更新
this.setState({ErrorAnswers:newObject})
}
render(){
const{random,errowanswers}=this.state;
返回(
{ErrorAnswers&&ErrorAnswers[random]。映射((ErrorAnswers,索引)=>{
{errowresponse}
})}
//你的其他代码。。。
);
}
}
您需要在您的状态中组合所有想要的对象,然后调用setState
一次。(setState是异步的,这样调用它50次肯定会得到一些意想不到的结果)为什么还要再次发布相同的问题?这一个已经解决了您的问题@HemadriDasari第一个解决方案改进了代码,但没有解决问题我现在还没有定义如果第一个解决方案不起作用,那么您应该向回答您问题的人进行评论和解释,而不是作为单独的问题发布。另外,如果答案没有解决问题,那么请不要将其视为已验证答案可能的副本,因此我应该在设置状态之前将所有逻辑保存在对象中?我建议您这样做。上面的代码只是一个展示,我看到你也有答案
和问题
数组,但从手机上编写代码并不有趣…:一定要记得尽可能地减少孩子的数量。非常感谢!这太棒了!很乐意帮忙。祝你好运