React hooks learning - "useState"

useState

1. The array pairs returned by useState appear, one-to-one corresponding to "data" and "method of modifying data".
2. When the data state is modified using the method, the function will be re-executed as a whole and rendered with the latest values.
3. Give the initial value to the parameter and take effect only when the function is first rendered.
import { useState } from 'react'function Learn_useState
function Learn_useState () {
     const [count, setCount] = useState(0)
     return(
         <div className="App">
             {count}
         <button onClick={() => setCount(count + 1)}>+</button>
         </div>
     )
 }
5. setSrate can pass in methods that can be used to process more complex data.
export default Learn_useState

import { useState } from "react";
// Processing of complex initial values
//Requirement: Initial value 50 member objects
//Summary: Pass a function to useState to do data operations inside the function and return the results

const createList = () => {
  //Calculation
  //Define Array
  const _list = [];
    for (let i = 0; i < 50; i++) {
      _list.push({
        id: i,
        text: "Item" + i,
      });
    }
    return _list;
  };

function Learn_useState() {
	
  //_returned from the createList method list as the initial value of useState.
  const [list, setList] = useState(createList);

  return (
    <div className="Learn_useState">
      <ul>
        {list.map((item) => (
          <li key={item.id}>{item.text}</li>
        ))}
      </ul>
    </div>
  );
}
6.React's comparison mechanism compares setState references, so if you want to change the state, you need to change the reference of the value to trigger page updates. (Light copy, deep copy)
import {useState} from 'react'
//Complex type modification problems

//react comparison mechanism: comparison references will not be updated if the reference is unchanged and will only be updated if the reference has changed

function Learn_useState (){
    const [obj,setObj] = useState({
        name: 'name'
    })
    const changeObj = () => {
        //The following two lines of writing do not change on the page after clicking because of the react comparison mechanism. (shallow copy)
        // obj.name = 'name'
        // setObj(obj.name)

        setObj({
            ...obj,
            name: 'name'
        })// Deconstruct a piece of data in a new object (the reference has changed) and then replace it (deep copy)
    }
    return (
        <div className='Learn_useState'>
            {obj.name}
            <button onClick={changeObj}>change</button>
        </div>
    )
}

export default Learn_useState
7.State modification merge:

a. Components will only be updated once when the same state is modified multiple times, whichever is the last.

b. When different states are modified at the same time, only one component update will occur, and one update will update more than one state.

8. Closure Problem - The closure problem is caused by the use of the state parameter in methods that do not require parameters. After the first rendering, the state gets its initial value. The reference to the state is maintained throughout the method, and the operations in the method use the initial value of the state.
import { useState } from 'react'
//Closure trapping problem

//Reason: When the App function components caused by closures are first rendered, all variables and functions inside the function are initialized
//The count recorded in setTimeout's callback is the count we started executing [0] 
//Like taking photos, every time an app executes the initialization count - setTimeout callback function, it uses the value of count at the time of App initialization!!!

// Solution: setCount ((precount) => count +1), the first parameter in setState method is the last state (preState)
// The parameter of the react default callback function is the latest value 
function Learn_useState() {
    const [count, setCount] = useState(0)
    const handle = () => {
        setCount(count + 1)
        setTimeout(() => {
            setCount(count => count + 2)
        }, 3000)
    }
    return (
        <div className="App">
            this is app{count} 
            <button onClick={handle}>+</button>
        </div>
    )
}

export default Learn_useState
9. useState asynchronous update. When the hook method is called to modify the state, the old value is immediately retrieved instead of the latest value. (It is easy to make a mistake as a judgement)
import {useState} from 'react'
// Asynchronous problem with useState value update

//Behavior: Immediately after calling the hook method to modify the state, the old value is not the latest value

//Attention as a condition of judgment

function Learn_useState () {
    const [count, setCount] = useState(0)
    const clickHandler = () => { 
        setCount(1)
        console.log(count);//count ?
        //Write a judgment to avoid value errors
        if(count === 1){
            console.log('Succeed');
        }
     }
     return (
        <button onClick={clickHandler}>change</button>
     )
}

export default Learn_useState
10. Don't use state to store "ready-to-wear", avoid manual synchronization of multiple states.
import {useState} from 'react'
// What kind of data principle should useState store?
// It is not recommended to store "synthetic" values!!
//Avoid manual synchronization of multiple states

//Display the current array length greater than 3 to the view

//Array length 1. New state [Multi-state synchronization control] 2. Direct calculation from existing state

function Learn_useState () {
    const [list, setList] = useState([1, 2])
    const [isThen3, setIsThen3] = useState(false)
    const changeList = () => {
        setList([...list, 3, 4, 5])
        setIsThen3(true)
    }
    return (
        <div>
            {isThen3 ? 'Array length greater than 3' : 'Array length less than 3'}
            <ul>
                {list.map(item => <li>(item)</li>)}
            </ul>
            <button onClick={changeList}>changeList</button>
        </div>
    )
}

export default Learn_useState
```### useState
###### 1. A pair of arrays returned by useState appears, one-to-one corresponding to "data" (state) and "method of modifying data" (setState). <br>

###### 2. When the data state is modified using the method, the function will be re-executed as a whole and rendered with the latest values.

###### 3. Give the initial value to the parameter and take effect only when the function is first rendered.

```js
import { useState } from 'react'function Learn_useState
function Learn_useState () {
     const [count, setCount] = useState(0)
     return(
         <div className="App">
             {count}
         <button onClick={() => setCount(count + 1)}>+</button>
         </div>
     )
 }
  1. setSrate can pass in methods that can be used to process more complex data.
export default Learn_useState

import { useState } from "react";
// Processing of complex initial values
//Requirement: Initial value 50 member objects
//Summary: Pass a function to useState to do data operations inside the function and return the results

const createList = () => {
  //Calculation
  //Define Array
  const _list = [];
    for (let i = 0; i < 50; i++) {
      _list.push({
        id: i,
        text: "Item" + i,
      });
    }
    return _list;
  };

function Learn_useState() {
	
  //_returned from the createList method list as the initial value of useState.
  const [list, setList] = useState(createList);

  return (
    <div className="Learn_useState">
      <ul>
        {list.map((item) => (
          <li key={item.id}>{item.text}</li>
        ))}
      </ul>
    </div>
  );
}

6.React's comparison mechanism compares setState references, so if you want to change the state, you need to change the reference of the value to trigger page updates. (Light copy, deep copy)

import {useState} from 'react'
//Complex type modification problems

//react comparison mechanism: comparison references will not be updated if the reference is unchanged and will only be updated if the reference has changed

function Learn_useState (){
    const [obj,setObj] = useState({
        name: 'name'
    })
    const changeObj = () => {
        //The following two lines of writing do not change on the page after clicking because of the react comparison mechanism. (shallow copy)
        // obj.name = 'name'
        // setObj(obj.name)

        setObj({
            ...obj,
            name: 'name'
        })// Deconstruct a piece of data in a new object (the reference has changed) and then replace it (deep copy)
    }
    return (
        <div className='Learn_useState'>
            {obj.name}
            <button onClick={changeObj}>change</button>
        </div>
    )
}

export default Learn_useState

7.State modification merge:

a. Components will only be updated once when the same state is modified multiple times, whichever is the last.

b. When different states are modified at the same time, only one component update will occur, and one update will update more than one state.

8. Closure Problem - The closure problem is caused by the use of the state parameter in methods that do not require parameters. After the first rendering, the state gets its initial value. The reference to the state is maintained throughout the method, and the operations in the method use the initial value of the state.
import { useState } from 'react'
//Closure trapping problem

//Reason: When the App function components caused by closures are first rendered, all variables and functions inside the function are initialized
//The count recorded in setTimeout's callback is the count we started executing [0] 
//Like taking photos, every time an app executes the initialization count - setTimeout callback function, it uses the value of count at the time of App initialization!!!

// Solution: setCount ((precount) => count +1), the first parameter in setState method is the last state (preState)
// The parameter of the react default callback function is the latest value 
function Learn_useState() {
    const [count, setCount] = useState(0)
    const handle = () => {
        setCount(count + 1)
        setTimeout(() => {
            setCount(count => count + 2)
        }, 3000)
    }
    return (
        <div className="App">
            this is app{count} 
            <button onClick={handle}>+</button>
        </div>
    )
}

export default Learn_useState
  1. useState asynchronous update. When the hook method is called to modify the state, the old value is taken immediately instead of the latest value. (It is easy to make a mistake as a judgment, and use useEffect to get a new value.)
import {useState} from 'react'
// Asynchronous problem with useState value update

//Behavior: Immediately after calling the hook method to modify the state, the old value is not the latest value

//Attention as a condition of judgment

function Learn_useState () {
    const [count, setCount] = useState(0)
    const clickHandler = () => { 
        setCount(1)
        console.log(count);//count ?
        //Write a judgment to avoid value errors
        if(count === 1){
            console.log('Succeed');
        }
     }
     return (
        <button onClick={clickHandler}>change</button>
     )
}

export default Learn_useState
  1. Do not use state to store "ready-to-wear", avoid manual synchronization of multiple states.
import {useState} from 'react'
// What kind of data principle should useState store?
// It is not recommended to store "synthetic" values!!
//Avoid manual synchronization of multiple states

//Display the current array length greater than 3 to the view

//Array length 1. New state [Multi-state synchronization control] 2. Direct calculation from existing state

function Learn_useState () {
    const [list, setList] = useState([1, 2])
    const [isThen3, setIsThen3] = useState(false)
    const changeList = () => {
        setList([...list, 3, 4, 5])
        setIsThen3(true)
    }
    return (
        <div>
            {isThen3 ? 'Array length greater than 3' : 'Array length less than 3'}
            <ul>
                {list.map(item => <li>(item)</li>)}
            </ul>
            <button onClick={changeList}>changeList</button>
        </div>
    )
}

export default Learn_useState

The above is your record of learning. Welcome to visit and guide you guys!!!

Tags: Front-end Javascript React

Posted by mikesheridan5 on Fri, 19 Aug 2022 01:39:10 +0930