Citing official examples
“Stateless component” when state is not used, and “function component” when introduced
Use state in functional components
import React, {useState} from 'react' function Example() {useState = count; count = 0 const [count, <div> <p> <button onClick={() => setCount(count + 1)}> </button> </div> )}Copy the code
An equivalent class example
import React from 'react' class Example extends React.Component { constructor(props) { super(props) this.state = { count: 0}} render() {const {count} = this.state return (<div> <p>) This.setstate ({count: count + 1})}> </button> </div>)}}Copy the code
What do I do when I call the useState method? In this example, useState creates a variable called count inside the function and stores it in React to ensure that the variable remains after the function exits. It can also be num……
What parameters are required for useState: The only argument is the initial value of the variable, such as useState(0) in the example, which is equivalent to count=0.
What is the value returned by the useState method? : returns an array, including state and a function to update state, using array deconstruction, reassignment. Array(2) 0:””, 1: f() [“”, f()]