React、React Router 和 Redux 常用Hooks 总结,提升您的开发效率!

发布于:2024-04-30 ⋅ 阅读:(20) ⋅ 点赞:(0)

Hooks 是 React 16.8 中引入的一种新特性,它使得函数组件可以使用 state 和其他 React 特性,从而大大提高了函数组件的灵活性和功能性。下面分别总结React、React Router 、Redux中常用的Hooks。
在这里插入图片描述

常用Hooks速记

React Hooks

useState:用于在函数组件中添加状态。
useEffect:用于在函数组件中执行副作用操作,如发送 AJAX 请求、订阅事件等。
useContext:用于在函数组件中消费上下文。
useReducer:用于在函数组件中管理状态,类似于 Redux 的 reducer。
useCallback:用于在函数组件中返回一个 memoized 回调函数。
useMemo:用于在函数组件中返回一个 memoized 值。
useRef:用于在函数组件中创建一个可变的引用对象。
useImperativeHandle:用于在函数组件中自定义暴露给父组件的实例值。
useLayoutEffect:用于在函数组件中执行同步布局效果。
useDebugValue:用于在 React 开发者工具中显示自定义 Hook 的标签。

React Router Hooks

useHistory:用于在函数组件中访问 history 对象。
useLocation:用于在函数组件中访问 location 对象。
useParams:用于在函数组件中访问 match 对象中的参数。
useRouteMatch:用于在函数组件中访问 match 对象。
useLinkClickHandler:用于在函数组件中处理 Link 组件的点击事件。

Redux Hooks

useSelector:用于从 Redux 存储中选择数据。
useDispatch:用于在函数组件中派发 Redux 动作。
useStore:用于在函数组件中获取 Redux 存储实例。
useActions:用于在函数组件中批量导入 Redux 动作创建函数。
useShallowEqual:用于在 useSelector 中进行浅层比较。
useDeepEqual:用于在 useSelector 中进行深层比较。
useRedux:用于在函数组件中获取 Redux 存储实例和派发函数。

以下是一些常用的 React、React Router 和 Redux Hooks 的示例代码:

React Hooks

  1. useState:用于在函数组件中添加状态。
import React, { useState } from 'react';

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
  1. useEffect:用于在函数组件中执行副作用操作,如发送 AJAX 请求、订阅事件等。
import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('https://api.example.com/data');
      const json = await response.json();
      setData(json);
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>Data:</h1>
      {data && <p>{data.message}</p>}
    </div>
  );
}
  1. useContext:用于在函数组件中消费上下文。
import React, { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemeButton() {
  const theme = useContext(ThemeContext);

  return (
    <button>{theme === 'light' ? 'Switch to Dark' : 'Switch to Light'}</button>
  );
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemeButton />
    </ThemeContext.Provider>
  );
}
  1. useReducer:用于在函数组件中管理状态,类似于 Redux 的 reducer。
import React, { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

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

  return (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
    </>
  );
}
  1. useCallback:用于在函数组件中返回一个 memoized 回调函数。
import React, { useState, useCallback } from 'react';

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

  const handleClick = useCallback(() => {
    setCount(count + 1);
  }, [count]);

  return <button onClick={handleClick}>Click me</button>;
}
  1. useMemo:用于在函数组件中返回一个 memoized 值。
import React, { useMemo } from 'react';

function Example({ a, b }) {
  const result = useMemo(() => {
    // 计算结果
    return a + b;
  }, [a, b]);

  return <div>{result}</div>;
}
  1. useRef:用于在函数组件中创建一个可变的引用对象。
import React, { useRef } from 'react';

function Example() {
  const inputRef = useRef();

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <input ref={inputRef} type="text" />
      <button onClick={handleClick}>Focus input</button>
    </>
  );
}
  1. useImperativeHandle:用于在函数组件中自定义暴露给父组件的实例值。
import React, { useRef, useImperativeHandle, forwardRef } from 'react';

const FancyInput = forwardRef((props, ref) => {
  const inputRef = useRef();

  useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    },
  }));

  return <input ref={inputRef} type="text" />;
});

function App() {
  const inputRef = useRef();

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <FancyInput ref={inputRef} />
      <button onClick={handleClick}>Focus input</button>
    </>
  );
}
  1. useLayoutEffect:用于在函数组件中执行同步布局效果。
import React, { useLayoutEffect, useRef } from 'react';

function Example() {
  const ref = useRef();

  useLayoutEffect(() => {
    // 同步布局效果
    console.log(ref.current.clientHeight);
  }, []);

  return <div ref={ref}>Hello World</div>;
}
  1. useDebugValue:用于在 React 开发者工具中显示自定义 Hook 的标签。
import React, { useMemo } from 'react';

function useCustomHook(value) {
  const result = useMemo(() => {
    // 计算结果
    return value * 2;
  }, [value]);

  // 在 React 开发者工具中显示自定义 Hook 的标签
  React.useDebugValue(`Result: ${result}`);

  return result;
}

function Example({ value }) {
  const result = useCustomHook(value);

  return <div>{result}</div>;
}

React Router Hooks

  1. useHistory:用于在函数组件中访问 history 对象。
import { useHistory } from 'react-router-dom';

function Example() {
  const history = useHistory();

  const handleClick = () => {
    history.push('/about');
  };

  return <button onClick={handleClick}>Go to About</button>;
}
  1. useLocation:用于在函数组件中访问 location 对象。
import { useLocation } from 'react-router-dom';

function Example() {
  const location = useLocation();

  return <div>{location.pathname}</div>;
}
  1. useParams:用于在函数组件中访问 match 对象中的参数。
import { useParams } from 'react-router-dom';

function Example() {
  const { id } = useParams();

  return <div>ID: {id}</div>;
}
  1. useRouteMatch:用于在函数组件中访问 match 对象。
import { useRouteMatch } from 'react-router-dom';

function Example() {
  const match = useRouteMatch();

  return <div>{match.path}</div>;
}
  1. useLinkClickHandler:用于在函数组件中处理 Link 组件的点击事件。
import { useHistory, useLinkClickHandler } from 'react-router-dom';

function Example() {
  const history = useHistory();
  const handleClick = useLinkClickHandler('/about');

  return (
    <button type="button" onClick={(event) => {
      handleClick(event, history);
    }}>
      Go to About
    </button>
  );
}

Redux Hooks

  1. useSelector:用于从 Redux 存储中选择数据。
import { useSelector } from 'react-redux';

function Example() {
  const count = useSelector(state => state.count);

  return <div>{count}</div>;
}
  1. useDispatch:用于在函数组件中派发 Redux 动作。
import { useDispatch } from 'react-redux';

function Example() {
  const dispatch = useDispatch();

  const handleClick = () => {
    dispatch({ type: 'increment' });
  };

  return <button onClick={handleClick}>Increment</button>;
}
  1. useStore:用于在函数组件中获取 Redux 存储实例。
import { useStore } from 'react-redux';

function Example() {
  const store = useStore();

  return <div>{store.getState().count}</div>;
}
  1. useActions:用于在函数组件中批量导入 Redux 动作创建函数。
import { useActions } from 'react-redux-actions';

function Example() {
  const { increment, decrement } = useActions({
    increment: () => ({ type: 'increment' }),
    decrement: () => ({ type: 'decrement' }),
  });

  return (
    <>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </>
  );
}
  1. useShallowEqual:用于在 useSelector 中进行浅层比较。
import { useSelector, shallowEqual } from 'react-redux';

function Example() {
  const { count, name } = useSelector(
    state => ({
      count: state.count,
      name: state.name,
    }),
    shallowEqual
  );

  return (
    <div>
      Count: {count}
      <br />
      Name: {name}
    </div>
  );
}
  1. useDeepEqual:用于在 useSelector 中进行深层比较。
import { useSelector, deepEqual } from 'react-redux';

function Example() {
  const { count, list } = useSelector(
    state => ({
      count: state.count,
      list: state.list,
    }),
    deepEqual
  );

  return (
    <div>
      Count: {count}
      <br />
      List: {list.join(', ')}
    </div>
  );
}
  1. useRedux:用于在函数组件中获取 Redux 存储实例和派发函数。
import { useRedux } from 'react-redux';

function Example() {
  const [store, dispatch] = useRedux();

  const handleClick = () => {
    dispatch({ type: 'increment' });
  };

  return (
    <div>
      Count: {store.getState().count}
      <br />
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

这些 Hooks 可以帮助您更方便地在 React、React Router 和 Redux 中管理状态和处理逻辑。根据实际需求选择合适的 Hooks 可以提高代码的可读性和可维护性。