React study notes three

react-hooks

Commonly used:

useState

const [state, setState] = useState(initialState);

In the initial state, state is the same as the value of the first parameter initialState passed in .

The setState function is used to update the state. 

eg:

import React, {useState} from 'react'
    export default function Test() {
        const [name, setname] = useState('zli')
        return (
            <div>
                {name} //'zli' 
                <button onClick={()=>{
                    setname('zll')//'zll'
                }}>changeName</button>   
            </div>
        )
    }
</script>

useEffect

const [name, setname] = useState('zli')
//副作用处理

useEffect(()=>{
    //如果在这里对name做了修改,那么数组中必须指明对应的依赖(即状态)
    setname(name.toUpperCase());
    return () => {
        console.log('在这里组件被销毁')
    }
},[name])

illustrate:

(1) If the second parameter is an empty array, then the first parameter will only go once;

(2) If [name] name exists as a dependency;

(3) As long as it is modified, the first parameter will go once;

(4) Here it can be regarded as reprocessing of state data.

useCallback


Prevent the method from being created again because the component is re-rendered, and act as a cache.

  const [name, setname] = useState('zli')
        const myFn = useCallback(()=>{
            console.log(name);
        },[name])

illustrate:

(1) Only when the name is changed, the function will be regenerated;

(2) If an empty array is passed in, the function will be generated for the first time, and will remain unchanged afterwards;

(3) If you do not pass an array, a new function will be generated every time.

use Memo

Perform calculations on state data and finally return a result.

const getResult = useMemo(()=>list.map(n=>n**2),[list])

useRef

const refContainer = React.useRef(initialValue)

useRef returns a mutable ref object whose .current property is initialized to the incoming parameter (initialValue)

Features:

  • useRef is a method that can only be used in function components;
  • useRef is the fourth method to get ref except string ref, function ref and createRef;
  • useRef never changes during the rendering cycle, so it can be used to refer to some data;
  • Modifying ref.current will not cause the component to re-render;
  • useRef persists after each re-render, while createRef changes each time.

Custom hooks:

(1) Must start with "use";

(2) When we want to share logic between two functions, we extract it into a third function;

(3) Reinterpretation: Encapsulate complex code into functions.

 

Guess you like

Origin blog.csdn.net/weixin_52993364/article/details/128145883