javascript - 反应:“状态”未定义 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 上的其他答案,但无济于事。奇怪的是,页面正确加载了一秒钟,却引发了错误。
任何帮助将不胜感激。谢谢你。
解决方案
由于您使用的是 Class 组件,因此您必须添加this
. 所以它变成this.state
了另请查看本指南在反应中管理状态
推荐阅读
- c - 如何简化这个 readLine() 函数?
- javascript - 使用增强现实创建 QR 码扫描仪
- java - Java:如果发生变化,同步不会阻塞
- javascript - D3.js如何在使用新数据时更新图表
- python - 如何在 QWidget 中的 matplot 画布上跟踪鼠标?
- variables - 在函数中调用带有空格的变量
- c# - 如何判断浮点除法的结果是否应该是整数?
- android - Graphhopper - 位置索引版本不正确
- javascript - 你可以混合使用 bootstrap 3.3 和 bootstrap 4.1 吗?我试过了,它破坏了网站
- angular - AngularMatTree 似乎知道有数据,但不会显示它