Don't do React for an intern who doesn't know these things. He was just criticized by the leader for causing a big disaster...

Although there are many things to learn about the React framework, and the types are very complex, an average intern can do it after just learning a few chapters, because the simple page logic is just that, but there are many details that need to be paid attention to, otherwise just write Page logic can also cause big trouble. Therefore, you must know these before you can safely create pages for novices.

1. No need to use State

Let's implement a page, but without using state management.

For example, you want to implement a prompt content. The result is this

let tip:string = 'tip content';

return (
<div>{tip}</div>
)

If the content of the tip changes, the page will not be refreshed if it is assigned to the tip.

state usage be like:

const [tipState,setTipState] = useState<string>('tip Content');

return(
    <div>{tipState}</div>
)

Every time the state changes, just use setTipState(xxx)

2. Abuse of State/Irregular State

It should be noted that useState will refresh the page in real time, but because of this reason, the page will be refreshed multiple times, which is very inconvenient.

If they are similar useStates, try to combine them and write them.

const [countState,setCountState] = useState<number>(0);
const [countTipState,setCountTipState] = useState<string>('now count is 1, total is 2');

return (
    <div>{countState}</div>
    <div>{countTipState}</div>
)

//改成

const [countState,setCountState] = useState<number>(0);

return (
    <div>{countState}</div>
    <div>{`now count is ${countState}, total is ${countState * 2}`}</div>
)

3. Do not write dependencies

useEffect, useCallback, useMemo, and useImperativeHandle all require writing dependencies. Otherwise, even if useState and props change, some states will not be synchronized. Dependencies must be checked regularly so that there will be no problem of state out-of-synchronization.

In fact, it is more convenient to use style management tools such as eslint. If something is missed, it will be checked.


const [countState,setCountState] = useState(0);
useMemo((
    console.log(countState);
)=>{},[countState])

useEffect((
    console.log(countState);
)=>{},[countState])

4. Abuse useRef

Ref is really convenient, it spans history and can be stored and retrieved at any time.

But it cannot be used too casually, as some assignments will lead to current hell.

be like:

const myRef = useRef(null);
const nowRef = useRef({a:10});

useEffect(()=>{
    myRef = nowRef.current;
    if(myRef.current.current.a === 10){
        console.log(myRef.current.current.a)
    }
},[])

5. Wait

There are also many mistakes made by js beginners such as === not written as ==, copying css, and irregular naming.

I have to get off work, I will update when I come back~

Guess you like

Origin blog.csdn.net/FishWooden/article/details/131323011