Javascript 无法访问';这';在ReactJS中
Javascript 无法访问';这';在ReactJS中,javascript,reactjs,Javascript,Reactjs,类问题扩展了React.Component{ 建造师(道具){ 超级(道具); this.randInt=Math.floor(Math.random()*1); } 问题={ 任务:问题[this.props.randInt].quest, 答案:问题[this.props.randInt]。答案, 正确:问题[this.props.randInt]。正确 } }改用this.randIntrandInt不是道具,而是在类上定义的 类问题扩展了React.Component{ 建造师(道具)
类问题扩展了React.Component{
建造师(道具){
超级(道具);
this.randInt=Math.floor(Math.random()*1);
}
问题={
任务:问题[this.props.randInt].quest,
答案:问题[this.props.randInt]。答案,
正确:问题[this.props.randInt]。正确
}
}
改用this.randInt
randInt
不是道具,而是在类上定义的
类问题扩展了React.Component{
建造师(道具){
超级(道具);
this.randInt=String(Math.floor(Math.random()*2)+1);
}
问题={
任务:问题[this.randInt].quest,
答案:问题[this.randInt]。答案,
正确:问题[this.randInt]。正确
}
}既然它是this.randInt
而不是this.props.randInt
,那么它应该是this.randInt
无处不在
问题
是一个,是构造函数代码的语法糖:
class Question extends React.Component{
constructor(props){
super(props);
this.question = {
quest : questions[this.props.randInt].quest,
answers : questions[this.props.randInt].answers,
correct : questions[this.props.randInt].correct
}
this.randInt = Math.floor(Math.random() * 1);
}
}
类字段声明首先在构造函数体中进行。由于此处不需要显式构造函数,因此应为:
class Question extends React.Component{
randInt = Math.floor(Math.random() * 1);
question = {
quest : questions[this.randInt].quest,
answers : questions[this.randInt].answers,
correct : questions[this.randInt].correct
}
}
对于类字段,只需要显式构造函数来处理以前在弃用的ComponentWillmount
生命周期方法中发生的同步副作用。您需要这个。问题而不是问题什么是问题?另外,您想用问题对象做什么?你想什么时候初始化它?这是一个从外部js文件导入的对象,而不是this.props.randInt
dothis.randInt
它仍然不工作并抛出相同的错误,Math.floor(Math.random()*1)
总是返回0
。你能提供问题对象吗。另外Math.floor(Math.random()*1)
返回0个问题={1:{quest:“fasfs”,答案:[1812183718641899],正确:1837},2:{quest:“fasfag”,答案:[2,3,4,5],正确:4}你的问题对象上没有0
键。显然它会出错。好吧,我尝试了Math.floor(Math.random()*2)+1,但SameContver它为string,因为你正在访问对象的属性