在反应中设置状态,但不断收到错误“状态”被分配一个值,但从未使用过no-unused-vars

我正在学习react.js状态,每次运行此代码时,我都会得到错误“状态”一个值,但从未使用过no-unused-vars

我试图使类APP代替功能APP

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


function App() {
  const state = {
   persons: [
  { name :'max',age : 28},{ name:'manu',age : 29},{ name:'adel',age : 30}
]
}
  return (
    <div classname="App">
      <h1> Hello world</h1>
      <button> Switch name </button>
      <Person name= {this.state.persons[0].name} age= {this.state.persons[0].age} ></Person>
      <Person name= {this.state.persons[1].name}  age= {this.state.persons[1].age} >hello eslam </Person>
      <Person name= {this.state.persons[2].name}  age= {this.state.persons[2].age} ></Person>

    </div>
  );
}

export default App;
nnn289 回答:在反应中设置状态,但不断收到错误“状态”被分配一个值,但从未使用过no-unused-vars

原因是这是一个功能。您需要使用state而非this.state来使用它。

,

您没有使用变量state,而是使用了this.state


此外,如果您想在功能中使用state中的react,则可能要使用hooks

以下链接可以帮助您开始:

状态和生命周期:https://reactjs.org/docs/state-and-lifecycle.html

挂钩状态:https://reactjs.org/docs/hooks-state.html

,

如果您在功能组件或标签render(){...}中使用变量和函数,则无需使用this

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

function App() {
  const state = {
    persons: [
      { name: 'max',age: 28 },{ name: 'manu',age: 29 },{ name: 'adel',age: 30 }
    ]
  };

  return (
    <div className='App'>
      <h1> Hello world</h1>
      <button> Switch name </button>
      <Person
        name={state.persons[0].name}
        age={state.persons[0].age}
      ></Person>
      <Person name={state.persons[1].name} age={state.persons[1].age}>
        hello eslam{' '}
      </Person>
      <Person
        name={state.persons[2].name}
        age={state.persons[2].age}
      ></Person>
    </div>
  );
}

export default App;
,

您应该使用这样的状态

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}

这是在状态中使用状态的基础,尽管还有另一种在状态中使用状态的方法,即Hooks,这是一个等效的示例:

import React,{ useState } from 'react';

function Example() {
  // Declare a new state variable,which we'll call "count"
  const [count,setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

有关更多信息,请参见:https://reactjs.org/docs/hooks-state.html

本文链接:https://www.f2er.com/3162018.html

大家都在问