React---函数组件的常用hook

 1. useState

import { useState } from 'react';

interface State {
  count: number;
}

function Counter() {
  const [state, setState] = useState({ count: 0 });

  return (
    

Count: {state.count}

); }

 2. useEffect

import { useEffect, useState } from 'react';

function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // 模拟数据获取
    setTimeout(() => {
      setData('Fetched data!');
    }, 1000);
  }, []); // 空数组表示只在组件挂载时运行

  return (
    

Data: {data}

); }

3. useContext 

import { createContext, useContext } from 'react';

interface ContextValue {
  value: string;
}

const MyContext = createContext({ value: 'Default Context Value' });

function ContextConsumer() {
  const contextValue = useContext(MyContext);

  return (
    

Context Value: {contextValue.value}

); }

4. useReducer 

import { useReducer } from 'react';

interface State {
  count: number;
}

type Action = { type: 'increment' };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    default:
      return state;
  }
}

function ReducerExample() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    

Count: {state.count}

); }

5. useCallback 

import { useCallback, useState } from 'react';

function CallbackExample() {
  const [count, setCount] = useState(0);

  const increment = useCallback(() => {
    setCount((prevCount) => prevCount + 1);
  }, []);

  return (
    

Count: {count}

); }

6. useMemo 

import { useMemo, useState } from 'react';

function MemoExample() {
  const [a, setA] = useState(1);
  const [b, setB] = useState(2);

  const result = useMemo(() => {
    console.log('Computing result...');
    return a + b;
  }, [a, b]);

  return (
    

Result: {result}

); }

7. useEffect 

import { useEffect, useRef } from 'react';

function RefExample() {
  const inputRef = useRef(null);

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus();
    }
  }, []);

  return (
    
); }

8. useImperativeHandle 

import { forwardRef, useImperativeHandle, useRef } from 'react';

interface MyComponentProps {
  // Props definition
}

interface MyComponentMethods {
  focus: () => void;
  // Other exposed methods
}

const MyComponent = forwardRef((props, ref) => {
  const internalRef = useRef(null);

  useImperativeHandle(ref, () => ({
    focus: () => {
      if (internalRef.current) {
        internalRef.current.focus();
      }
    },
    // Other exposed methods or values
  }), []);

  return (
    
); }); // Usage function ImperativeHandleExample() { const myRef = useRef(null); useEffect(() => { if (myRef.current) { myRef.current.focus(); } }, []); return (
); }

你可能感兴趣的:(react.js,前端,typescript)