变量状态未定义,但是

时间:2019-08-01 13:52:14

标签: reactjs

我从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;

2 个答案:

答案 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}/>