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
do
this.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,因为你正在访问对象的属性