React.FC detailed explanation

1. React.FC is a functional component that uses a generic type in TypeScript . FC is the abbreviation of FunctionComponent. In fact, React.FC can be written as React.FunctionComponent

const App: React.FunctionComponent<{ message: string }> = ({ message }) => (
    <div>{ message }</div>
);

//简写
interface PropsType{
  message : string;
}
const App: React.FC<PropsType> = ({ message }) => ( //{ message }相当于解构赋值,从props中解构
    <div>{ message }</div>
);

//声明了一个函数组件App   泛型为{message: string}  
//我能不能这么理解  泛型就是给组件里面使用的参数指定类型 

2.  React.FC Contains generic types without explicitly declaring types.  It is explicit for the return type, while the normal function version is implicit (otherwise an additional annotation is required). PropsWithChildren  props.children React.FC<>

3. React.FCProvides static properties for type checking and auto-completion: displayName, propTypesand defaultProps(Note: There are some problems when combined defaultPropswith React.FC ).

4. When we use React.FCto write React components, we can't use setState , instead we use Hook API such as useState(),useEffect etc.

//组件实现实时时间刷新显示
import React, {useState, useEffect} from 'react'; //引入依赖
export App: React.FC<{}> = (props) => { //泛型里面有对象{ 属性名 }(解构)  泛型为空对象就直接写props
    const [date, setDate] = useState(new Date());  //useState()括号里面的值给date
    useEffect(() => {
        const timer = setInterval(() => {
            setDate(new Date()); //setDate() 括号里面的值给date   date的值只能通过setDate()设置
        }, 1000)
    }, []);
    return (
        <div>
            <h3>现在时间是</h3>
            <p>{ date.toLocaleTimeString }</p>
        </div>
    )
}  

(1)const [date, setDate] = useState(new Date());

(2) useState is very simple, it is equivalent to the state in the class functional component, useState (value), where the value represents the initialization value, date represents the received value, and setDate represents the set value

(3) UseEffect Hook can be regarded as a combination of three functions: componentDidMount (component mount complete), componentDidUpdate (component update complete) and componentWillUnmount (component destroy call)

(4) The parameters in brackets [] at the end of useEffect indicate that when this parameter is updated, the method in it will be executed again. If there is no parameter, it will be empty.

(5) The return in useEffect indicates the action performed when the component is uninstalled ,

(6) useEffect will be executed once after the component is loaded , so in the first item, it can control three life cycles

(7) If there is no following parameter , or even [] , that is, useEffect(()=>{}), in this case, whenever the value of useState changes in the page , the code in useEffect will be executed once , which is Not advisable! !

Guess you like

Origin blog.csdn.net/qq_52421092/article/details/127628465