首页 > 解决方案 > 反应:“状态”未定义 no-undef

问题描述

我目前正在学习 React 入门课程,并在尝试编译我的代码时收到以下错误:

src/App.js
  Line 6:5:  'state' is not defined  no-undef

这是我的主要 React 组件中的代码:

import React from 'react';
import './App.css';
import Person from './Person/Person.js';

class App extends React.Component {
    state = {
      persons: [
        { name: 'Max', age: 28 },
        { name: 'Manu', age: 29 },
        { name: 'Stephanie', age: 26 }
      ],
      otherState: 'some other value'
    }

  render() {
    return (
      <div className="App">
        <h1>Does this work now?</h1>
        <p>This is really working</p>
        <button>Switch Name</button>
        <Person name={this.state.persons[0].name} age={this.state.persons[0].age}> My Hobbies: Racing</Person>
        <Person name={this.state.persons[1].name} age={this.state.persons[1].age}> My Hobbies: Racing</Person>
        <Person name={this.state.persons[2].name} age={this.state.persons[2].age}> My Hobbies: Racing</Person>
      </div>
    );
   // return React.createElement('div', {className: 'App'}, React.createElement('h1', null, 'does this work now'));
  }
}
export default App;

我已经尝试了一切,从准确复制讲师的代码,到查看 Stack 上的其他答案,但无济于事。奇怪的是,页面正确加载了一秒钟,却引发了错误。

任何帮助将不胜感激。谢谢你。

标签: javascriptreactjs

解决方案


由于您使用的是 Class 组件,因此您必须添加this. 所以它变成this.state 了另请查看本指南在反应中管理状态


推荐阅读