Understand the usage of Hooks state in react (case explanation)

foreword

This article takes you to learn the usage of hooks in react, and I also record it during the learning process. If there is any inappropriate summary, you are welcome to point it out and communicate together~

Introduction to Hooks

Why Hooks Appear

1. In our previous study of react, we know that the class component can define its own state to save the component's own internal state, and the function component has no state, because the variables of the functional component are local, each time Calls will open up new space and new variables. After the function is finished, the variables will be recycled.
2. The class component has a life cycle, we can complete our own logic in the corresponding life cycle, and the class component will re-execute the render method when the state changes. When functional components are re-rendered, they will all be executed, there is no way to call componentDidUpdate, and they have no state of their own.

What is Hook

Hooks are a new feature in React 16.8. It lets you use state and other React features (lifecycle methods) without writing class components.
The emergence of Hook is groundbreaking, it solves many problems that existed in React before, such as the nesting problem of HOC.

Hook usage scenarios

  1. The emergence of Hook can basically replace the calss component we used before
  2. In old projects, there is no need to refactor directly to Hook
  3. Hooks can only be used in function components, not in class components, or outside of function components

Hook usage principles

  1. Do not use Hooks in loops, conditional judgments or branches, only in the outermost layer of functions
  2. You can only use hooks in react function components
  3. We call it a hook in a useState alone, and Hooks is a general term for a class of Hooks.

Hook implements accumulator

Before using the hook, let's implement the accumulator using the class component we learned earlier:

export class Add extends Component {
    
    
    state = {
    
     count: 1 }
    render() {
    
    
        return (
            <div>
                <h1>{
    
    this.state.count}</h1>
                <button onClick={
    
    this.add}>点击</button>
            </div>
        )
    }
    
    add = () => {
    
    
        this.setState({
    
    count: this.state.count + 1})
    }
}

It's relatively simple, and everyone should be able to implement it quickly. Let's use hooks to implement this accumulator:
1. We need to refer to a new thing useState in the header, and we need to use it later.
2. UseState itself is a function, and it returns a function after calling Array, the first item is the state, the second item is the function method to modify and set our state
3. Define a state to receive arr[0], define the variable setState as arr[1], that is, get the second function
4. Bind click events to buttons to achieve cumulative effect

import React, {
    
     useState } from 'react'
export default function App() {
    
    
    const arr = useState(0)
    const state = arr[0]
    const setState = arr[1]
    return (
        <div><h1>Hook</h1>
            <p>{
    
    state}</p>
            <button onClick={
    
    (e) => setState(state + 1)}>点击</button>
        </div>
    )
}

Achievement effect:
insert image description here
Of course, we can also use destructuring to simplify the code here:

export default function App() {
    
    
    const [state, setState] = useState(0)
    return (
        <div>
            <p>{
    
    state}</p>
            <button onClick={
    
    (e) => setState(state + 1)}>+1</button>
            <button onClick={
    
    (e) => setState(state - 1)}>-1</button>
        </div>
    )
}

insert image description here

Multiple states (cases)

The above is a state, let's see how multiple states operate, write a simple example:
1. First, useState is introduced in the header
2. Then the data to be used is structured, and the arrays and objects are also defined here. Data type
3. You can use {age} directly where you need to use
it. 4. Where you need to operate, you can use the second function of the structure to operate. The button here is to add elements to the city array.

import React, {
    
     useState } from 'react'

export default function App() {
    
    
    const [age, setAge] = useState(18)
    const [money, setMoney] = useState(1000000000)
    const [city, setStar] = useState(['北京', '上海', '广州'])
    const [obj, setObj] = useState({
    
    name: '张三', age: 14})
    return (
        <div>
            <h1>张三同学: {
    
    age}</h1>
            <h2>他的存款: {
    
    money}</h2>
            <ul>
                {
    
    
                    city.map((item, index) => {
    
    
                        return (<li key={
    
    item}>{
    
    item}</li>)
                    })
                }
            </ul>
            <h3>{
    
    obj.name}今年{
    
    obj.age}</h3>
            <button onClick={
    
    e=>{
    
    setStar([...city, '深圳'])}}>给数组加元素</button>
        </div>
    )
}

Achievement effect:
·insert image description here

complex state (case)

Here we implement a case of simulating a movie ticket. Clicking the button can adjust the ticket price.
1. I will not talk about deconstructing the data before
. 2. Here, we need to click the button behind each item to change the ticket price of the corresponding item, so in In the function, the index subscript needs to be passed in
. 3. Then in the function, first copy a copy of the operation array, then change the price of the data item corresponding to the index, and finally modify it with setMovies

export default function App() {
    
    
    const [movies, setMovies] = useState([
        {
    
    id: 1, name: '守岛人', price: 50},
        {
    
    id: 2, name: '1921', price: 35},
        {
    
    id: 3, name: '哆啦A梦', price: 60},
        {
    
    id: 4, name: '中国医生', price: 40},
        {
    
    id: 5, name: '时间规划局', price: 55}
    ])

    function changePrice(index) {
    
    
        console.log(index)
        const movieList = [...movies]
        movieList[index].price += 5
        setMovies(movieList)
    }

    return (
        <div>
            <ul>
                {
    
    
                    movies.map((item, index) => {
    
    
                        return (
                            <li key={
    
    item.id}>
                                <span>电影名:{
    
    item.name}</span>
                                <span>票价:{
    
    item.price}</span>
                                <button onClick={
    
    e => changePrice(index)}>涨价了</button>
                            </li>
                        )
                    })
                }
            </ul>
        </div>
    )
}

Use previous state value

If we need to use the previous state value to change the existing state value, how should we do it?
Look at the following example: the requirement is to do an operation
1 that accumulates 100.If the new state needs to be calculated or manipulated by using the previous state, we can use a function passed to setstate, this function can receive the previous value and return the updated value
2. So in the click event, use the parameter of setstate, which is the previous state, to operate on this parameter

export default function App() {
    
    
    const [state, setstate] = useState(() => 100)
    return (
        <div>
            <h1>{
    
    state}</h1>
            <button onClick={
    
    e => setstate((prev) => prev + 100)}>+100</button>
        </div>
    )
}

At last

This document ends here. It mainly introduces the usage of states in hooks. The next article will continue to explain the knowledge related to hooks and its life cycle~

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/123587299