1 useState
2 useEffect
3 useContext
4 useReducer
Article directory
1 useState saves component state
useState
The role of is to declare and update variables, and the parameters received by the function are the initial values of our declared variables.
It returns an array, the first item is the current state value, and the second item is the method function that can change the state value.
1.1 Declare variables
Declare a variable count with an initial value of 0.
At the same time, a function setCount that can modify the count is provided.
const [count, setCount] = useState(0)
1.2 Using variables
Using variables is very simple, just use them directly or wrap them in curly braces.
<div>数量:{
count}</div>
1.3 Update Status
Just pass in the new value by calling the function setCount that modifies the count.
setCount(count + 1)
1.4 Complete example
import React, {
useState } from 'react'
const Test = () => {
const [count, setCount] = useState(0)
const addCount = () => {
// setCount(count + 1)// 第一更新种方式
setCount(count => count + 1)// 第二种更新方式
}
return (
<>
<div>数量:{
count}</div>
<button onClick={
addCount}>加1</button>
</>
)
}
export default Test