我从React开始,接着是Ninja React网络教程,它对我不起作用Complete React Tutorial (& Redux) #14 - Outputting Lists
我不断收到相同的错误:
无法编译。
./ src / App.js
第6行:“状态”未定义为un-undef
搜索关键字以详细了解每个错误。
我和他有相同的密码
import React from 'react';
import Footer from './footer';
function App() {
state = {
employes : [
{nom:'Mehdi',age:20,id:1},
{nom:'Khalil',age:22,id:2},
{nom:'Wael',age:26,id:3}
]
}
return (
<div className="App">
<header className="App-header">
<p>
<h1>This is my first react app :)</h1>
</p>
<Footer employes={this.state.employes}/>
</header>
</div>
);
}
export default App;
答案 0 :(得分:0)
您正在使用大写的S
定义状态,并且正在定义一个功能组件(不包含this.state
)。
将其设置为小写,然后将其更改为类组件,或使用useState
钩子:
class App extends Component {
state = {
employes : [
{nom:'Mehdi',age:20,id:1},
{nom:'Khalil',age:22,id:2},
{nom:'Wael',age:26,id:3}
]
}
render() {
return (
<div className="App">
<header className="App-header">
<p>
<h1>This is my first react app :)</h1>
</p>
<Footer employes={this.state.employes}/>
</header>
</div>
);
}
}
使用useState
钩子:
const App = function() {
const [employes, setEmployes] = useState([
{nom:'Mehdi',age:20,id:1},
{nom:'Khalil',age:22,id:2},
{nom:'Wael',age:26,id:3}
]);
return (
<div className="App">
<header className="App-header">
<p>
<h1>This is my first react app :)</h1>
</p>
<Footer employes={employes}/>
</header>
</div>
);
}
答案 1 :(得分:0)
两种解决问题的方法。您需要定义state
,
const state = {
employes : [
{nom:'Mehdi',age:20,id:1},
{nom:'Khalil',age:22,id:2},
{nom:'Wael',age:26,id:3}
]
}
使用功能组件时,您无权访问this
,可以将数据用作
<Footer employes={state.employes}/>
另一种方法是使用Hook
。对于功能组件,您具有useState
钩子。 useState
钩子返回一对getter
/ setter
。
const [employes, setEmployes] = useState([
{nom:'Mehdi',age:20,id:1},
{nom:'Khalil',age:22,id:2},
{nom:'Wael',age:26,id:3}
]);
用法
<Footer employes={employes}/>