本文发布于972天前,最后更新于 972 天前,其中的信息可能已经有所发展或是发生改变。
React为函数组件提供了一些React Hooks,来让函数组件也能拥有类组件的一些特性。
常用Hooks
- useState 在函数中使用state
- useEffect 用于在函数组件中使用生命周期
- useContext 不使用组件嵌套就可以订阅 React的Context
- useRef 返回一个可变的 ref 对象,其 .current属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内保持不变。
- useMemo 返回一个memoized值。,它仅会在某个依赖项改变时才重新计算,有助于避免在每次渲染时都进行高开销的计算。
- useCallback 返回一个memoized回调函数。把内联回调函数及依赖项数组作为参数传入useCallback,它将返回该回调函数的memoized版本,该回调函数仅在某个依赖项改变时才会更新。
部分用法示例
useState
首先看他在type.d.ts中的原型
// Unlike the class component setState, the updates are not allowed to be partial
type SetStateAction<S> = S | ((prevState: S) => S);
// this technically does accept a second argument, but it's already under a deprecation warning
// and it's not even released so probably better to not define it.
type Dispatch<A> = (value: A) => void;
/**
* Returns a stateful value, and a function to update it.
*
* @version 16.8.0
* @see https://reactjs.org/docs/hooks-reference.html#usestate
*/
useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];可以推测出他的用法为
const [var, setVar] = useState(initValue);
其中var为变量名,setVar为设置var的回调函数,修改var的值都需要通过该回调函数。
initValue为var的初始值。
示例
export const DemoComponent: React.FC = () => {
    const [time, setTime] = useState([new Date().toString()]);
    return <div>{time}</div>;
};测试输出
Fri Mar 03 2023 19:02:05 GMT+0800 (China Standard Time)useEffect
还是看他的原型
// NOTE: callbacks are _only_ allowed to return either void, or a destructor.
type EffectCallback = () => (void | Destructor);
type DependencyList = ReadonlyArray<unknown>;
/**
 * Accepts a function that contains imperative, possibly effectful code.
 *
 * @param effect Imperative function that can return a cleanup function
 * @param deps If present, effect will only activate if the values in the list change.
 *
 * @version 16.8.0
 * @see https://reactjs.org/docs/hooks-reference.html#useeffect
 */
function useEffect(effect: EffectCallback, deps?: DependencyList): void;
示例
export const DemoComponent: React.FC = () => {
    const [count, setCount] = useState(0);
    useEffect(() => {
        return () => {
            console.log('unMounted');
        };
    }, []);
    useEffect(() => {
        console.log('count++');
    }, [count]);
    return (
        <div>
            <button onClick={() => setCount(count + 1)}>Count {count}</button>
        </div>
    );
};其中以下代码可以被用作onMount和unMount生命周期函数
useEffect(()=>{
  console.log('onMount')
  return ()=>{
        console.log('unMounte')
  }
},[])




