javascript - 访问状态变量

标签 javascript reactjs

我无法访问 App 类中的状态变量。有人可以推荐我一些解决方案吗?

class App extends React.Component {
  constructor(props) {
    super(props);

    var question1 = [
      "What is 8*1",
      "What is 8*2",
      "What is 8*3",
      "What is 8*4"
    ];
    var choice = ["1", "2", "4", "8", "9"];
    this.state = {
      question1: this.question1,
      choice: this.choice,
      correct: 0,
      incorrect: 0
    };
    console.log(this.state.choice);
    this.clickHandler = this.clickHandler.bind(this);
  }
  clickHandler() {
    console.log("hello world");
  }
  render() {
    return (
      <div>
        <Question question={this.state.question1} choice={this.state.choice} />
      </div>
    );
  }
}

最佳答案

删除 this.question1this.choice 中的 this 并且总是更喜欢 let/const 而不是 var;

constructor(props) {
    super(props);

    const question1 = [
      "What is 8*1",
      "What is 8*2",
      "What is 8*3",
      "What is 8*4"
    ];
    const choice = ["1", "2", "4", "8", "9"];
    this.state = {
      question1: question1,
      choice: choice,
      correct: 0,
      incorrect: 0
    };
    this.clickHandler = this.clickHandler.bind(this);
  }

关于javascript - 访问状态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62169585/

相关文章:

javascript - Cytoscape js 阻止输入标签的 onChange 函数

javascript - 如何使用简单的 'a' 标签在现有网站中包含使用 npm 和 webpack 构建的 vuejs 应用程序?

javascript - Prop 类型 : array of one of the class instance

javascript - Webpack 构建语法错误 : Unexpected token )

javascript - 使用 JWT 测试经过身份验证的路由失败,使用 Mocha + supertest + passport

单击提交按钮时 JavaScript 代码输出两次

javascript - Jquery 关闭自动完成列表

reactjs - React JS UI 的 Backbone 路由器

javascript - 分配的响应数据显示 [object object] React Native

javascript - 如何将 jQuery 与 React js 集成?