useState()挂钩在reacts.js中如何工作?

时间:2020-01-27 08:19:57

标签: javascript reactjs

我是React.js的新手,下面是我的代码

import React,{useState} from 'react';
import './App.css';
import Person from './Person/Person'

const App = props =>
{
  const [personState, setPersonState] = useState({
    persons : [
      {name:"Max", age:28},
      {name:"Manu", age:29},
      {name:"Ranjeet", age:25}
    ],
    otherState : 'Some state value'
  }
  );
  console.log(personState);
  const switchNameHandler = () =>{
    setPersonState({
      persons : [
        {name:"Maximillian", age:28},
        {name:"Manu", age:29},
        {name:"Ranjeet", age:24}
      ],
      otherState : personState.otherState
    });

  }
// function App() {

      return (
        <div className="App">
          <h1>React App</h1>
          <p>This is working</p>
          <button onClick={switchNameHandler}>Switch Name</button>
          <Person name={personState.persons[0].name} age={personState.persons[0].age}/>
          <Person name={personState.persons[1].name} age={personState.persons[1].age}>My Hobbies:Racing</Person>
          <Person name={personState.persons[2].name} age={personState.persons[2].age}/>

        </div>
      );


}

export default App;

这里我在switchNameHandler函数中没有console.log(personState),但是在控制台中显示,当调用switchNameHandler时,是因为useState()钩子或其他原因

{persons: Array(3), otherState: "Some state value"}
otherState: "Some state value"
persons: Array(3)
0: {name: "Maximillian", age: 28}
1: {name: "Manu", age: 29}
2: {name: "Ranjeet", age: 24}
length: 3
__proto__: Array(0)
__proto__: Object 

1 个答案:

答案 0 :(得分:2)

是的是因为useState。

在此代码中,每次渲染您的App组件时都会调用console.log。

至少在渲染整个应用程序时或您的应用程序组件状态更改时至少一次。在您的示例中,useState创建了一些状态,并且您的点击处理程序更改了该状态,因此App组件被重新渲染。