join us!
160fe3a54202a5 " , to provide front-end developers with technical information and a series of basic articles. For a better user experience, please move to our official website novices (160fe3a54202ad https://xhs-rookies.com/ ) to learn and get the latest articles in time.
"Code tailor" , if you are interested in our article or want to make some suggestions, follow "Novices of Xiaohe Mountain" public account, contact us, you can also watch it on WeChat Our article. Every suggestion or approval is a great encouragement to us!
Why should we learn hooks
Preface
In this article, our main purpose is to understand the use of state hook (useState)
useState
definition
useState()
used to introduce state for the function component. Pure functions cannot have state, so use hooks to introduce state.
how to use
useState
is as follows.
const [count, setCount] = useState(defaultValue) // 假设 defaultValue 为 0
let countVariable = useState(0)
let count = countVariable[0]
let setCount = countVariable[1]
setCount(count + 1) // count 1
setCount(10) // count 10
const [name, setName] = useState('xhs')
const [age, setAge] = useState(18)
const [dowhat, setDowhat] = useState({ thing: 'Learn Hooks' })
setName('xxxxxxxhs')
setAge(20)
setDowhat({ thing: 'Learn Nothing' })
import React, { Component } from 'react'
import './App.css'
export class App extends Component {
constructor(props) {
super(props)
this.state = {
count: 0,
}
}
handleWithAddOne() {
this.setState({ count: this.state.count + 1 })
}
handleWithAddTwo() {
this.setState({ count: this.state.count + 2 })
}
handleWithDecreaseOne() {
this.setState({ count: this.state.count - 1 })
}
render() {
const { count } = this.state
return (
<div className="app">
<p>Now,the number is {count}.</p>
<div className="three-btn">
{/* 点击之后 count + 1 */}
<button className="button add" onClick={() => this.handleWithAddOne()}>
Click it, the number will add 1
</button>
{/* 点击之后 count + 2 */}
<button className="button add" onClick={() => this.handleWithAddTwo()}>
Click it, the number will add 2
</button>
{/* 点击之后 count - 1 */}
<button className="button decrease" onClick={() => this.handleWithDecreaseOne()}>
CLick it, the num will decrease 1
</button>
</div>
</div>
)
}
}
.app {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.three-btn {
display: flex;
flex-direction: column;
}
.button {
height: 40px;
margin: 12px 0px;
color: white;
border: none;
border-radius: 10px;
}
.add {
background-color: #1890ff;
}
.decrease {
background-color: red;
}
Use multiple useState
to define multiple state
variables.
useState
returns is an array, generally use destructuring assignment to get two values directly, state
and modify the state function. These two values need to be obtained in pairs.
useState
function, only need to pass in a unique parameter, as the default value, initialize state
.
Now, let us summarize useState
.
summary
Simply put, useState
is provided as a function of the components of the React state
functions can now be called function components , and before that, called stateless components .
In this way, we successfully used useState
. The results of the operation are the same as those of the above class components. The complexity of the code is greatly reduced. Compared with the class components, this method may be more acceptable to people. .
import './App.css' // 导入css样式,样式同上
import { useState } from 'react'
function App() {
const [count, setCount] = useState(0)
return (
<div className="app">
<p>Now,the number is {count}.</p>
<div className="three-btn">
<button className="button add" onClick={() => setCount(count + 1)}>
Click it, the number will add 1
</button>
<button className="button add" onClick={() => setCount(count + 2)}>
Click it, the number will add 2
</button>
<button className="button decrease" onClick={() => setCount(count - 1)}>
CLick it, the num will decrease 1
</button>
</div>
</div>
)
}
Let's complete the requirements:
We state
the value of useState
with setCount
and modify the value of count
Use useState to rewrite the case
Next, let's take a look at how useState
is implemented.
From the above, we can see that although the effect has reached our expectations, we can clearly feel that its code is very "heavy". In our real project development, React App
is composed of multiple classes, according to the hierarchy , Composed of layers, the degree of complexity can be imagined. At this time, if we are adding Redux
, it will become more complicated and cumbersome.
This is the rendering after running
css
style
First, let's look at class components, we use state
situation, we need to state
declare variables count
, and given a default value 0
, but only by modifying the way this.setState()
of count
be modified.
Class components are implemented using this.state
I want to have a simple counter, which requires +1
, +2
and -1
, to refresh the current numer
value on the page.
Now that you and useState
, then we will complete a requirement:
Comparison component
How to modify these variables? As above, just call the respective set
method directly.
The above statement can only declare one state
variable. If you want to declare multiple state
variables, you only need to use multiple useState
variables.
Use multiple state variables
First, the implementation of the first setCount
after the value from 0 -> 1
, when the second execution directly into a 10
, but its value from direct 1 -> 10
so count
updated values for the 10
.
To modify state
, you only need to directly use the setCount
method to change it. The incoming value will be directly returned to the count
value and updated. Such as the following two.
modify state
In other words, using useState
returns an array, which is equivalent to the following code:
What is returned is an array, but it will be JavaScript grammar array into two values, currently state
and modify the state function. This is
class
to this.state.count
and this.setState
, the only difference is that you need to obtain them in pairs.
useState return value
It defines a named count
of state
variable, it class
inside this.state
identical functionality provided. In general, after the function exits the variable will "disappear" while state
the variables are React
reserved.
What does
useState
needs to pass in is to initialize state
. We can pass various types of values, such as numbers, characters, arrays, objects, etc.
useState parameters
Preview of the next section
In the next section, we will introduce useEffect
to everyone, so stay tuned!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。