1、自定义请求Hooks

  1. import React, { useState, useCallback } from "react";
  2. const useAsync = (asyncFunction) => {
  3. const [data, setData] = useState(null);
  4. const [loading, setLoading] = useState(false);
  5. const [error, setError] = useState(null);
  6. const execute = useCallback(() => {
  7. setLoading(true);
  8. setData(null);
  9. setError(null);
  10. return asyncFunction()
  11. .then((response) => {
  12. setData(response);
  13. setLoading(false);
  14. })
  15. .catch((error) => {
  16. setError(error);
  17. setLoading(false);
  18. });
  19. }, [asyncFunction]);
  20. return { execute, loading, data, error };
  21. };
  22. export default function Test() {
  23. const { execute, data, loading, error } = useAsync(async () => {
  24. const res = await fetch("https://url");
  25. return res;
  26. });
  27. }

2、全局Modal对话框

  1. const modalReducer = (state = {}, action) => {
  2. const { modalId, status } = action.payload;
  3. switch (action.type) {
  4. case "modal/handleModalVisible":
  5. return {
  6. [modalId]: status,
  7. };
  8. default:
  9. return state;
  10. }
  11. };
  12. function changeModalVisible(modalId, status) {
  13. return {
  14. type: "modal/handleModalVisible",
  15. payload: {
  16. modalId,
  17. status,
  18. },
  19. };
  20. }
  21. // 创建自定义 Hook 用于处理对话框逻辑
  22. export const useNiceModal = ({ dispatch, modalId }) => {
  23. const [visible, setVisible] = useState(false);
  24. const handleModalVisible = useCallback(
  25. (status) => {
  26. dispatch(changeModalVisible(modalId, status)).then((res) => {
  27. setVisible(res);
  28. });
  29. },
  30. [dispatch, modalId]
  31. );
  32. return { handleModalVisible, visible };
  33. };
  34. // 使用
  35. function NiceModal({ id, dispatch, children }) {
  36. const { handleModalVisible, visible } = useNiceModal({
  37. dispatch,
  38. modalId: id,
  39. });
  40. return (
  41. <Modal
  42. onCancel={() => handleModalVisible(false)}
  43. onOk={handleModalVisible(true)} // 默认点击确定关闭对话框
  44. visible={visible}
  45. >
  46. {children}
  47. </Modal>
  48. );
  49. }

3、使用 Hooks 简化表单处理

  1. const useForm = (initialValues = {}) => {
  2. // 设置整个 form 的状态:values
  3. const [values, setValues] = useState(initialValues);
  4. // 提供一个方法用于设置 form 上的某个字段的值
  5. const setFieldValue = useCallback((name, value) => {
  6. setValues((values) => ({ ...values, [name]: value }));
  7. }, []);
  8. // 返回整个 form 的值以及设置值的方法
  9. return { values, setFieldValue };
  10. };
  11. // 使用
  12. export default () => {
  13. const { values, setFieldValue } = useForm();
  14. return (
  15. <input
  16. value={values.name || null}
  17. onChange={(evt) => setFieldValue("name", evt.target.value)}
  18. />
  19. );
  20. };

4、定义状态

  1. import { useState, useCallback }from 'react';
  2. function useCounter() {
  3. // 定义 count 这个 state 用于保存当前数值
  4. const [count, setCount] = useState(0);
  5. //实现加1的操作
  6. const increment = useCallback(() => setCount(count + 1), [count]);
  7. //实现减1的操作
  8. const decrement = useCallback(() => setCount(count - 1), [count]);
  9. // 重置计数器
  10. const reset = useCallback(() => setCount(0), []);
  11. // 将业务逻辑的操作 export 出去供调用者使用
  12. return { count, increment, decrement, reset };
  13. }
  14. // 使用
  15. import React from 'react';
  16. function Counter() {
  17. // 调用自定义 Hook
  18. const { count, increment, decrement, reset } = useCounter();
  19. //渲染UI
  20. return (
  21. <div>
  22. <button onClick={decrement}> - </button> <p>{count}</p>
  23. <button onClick={increment}> + </button> <button onClick={reset}> reset </button>
  24. </div>
  25. );
  26. }

5、监听浏览器状态

  1. import { useState, useEffect } from 'react';
  2. // 获取横向,纵向滚动条位置
  3. const getPosition = () => {
  4. return {
  5. x: document.body.scrollLeft, y: document.body.scrollTop,
  6. };
  7. };
  8. const useScroll = () => {
  9. // 定一个 position 这个 state 保存滚动条位置
  10. const [position, setPosition] = useState(getPosition());
  11. useEffect(() => {
  12. const handler = () => {
  13. setPosition(getPosition(document));
  14. };
  15. // 监听 scroll 事件,更新滚动条位置
  16. document.addEventListener("scroll", handler);
  17. return () => {
  18. // 组件销毁时,取消事件监听
  19. document.removeEventListener("scroll", handler);
  20. };
  21. }, []);
  22. return position;
  23. };
  24. import React, { useCallback } from 'react';
  25. import useScroll from './useScroll';
  26. function ScrollTop() {
  27. const { y } = useScroll();
  28. const goTop = useCallback(() => {
  29. document.body.scrollTop = 0;
  30. }, []);
  31. const style = {
  32. position: "fixed", right: "10px", bottom: "10px",
  33. };
  34. // 当滚动条位置纵向超过 300 时,显示返回顶部按钮 if(y>300){
  35. return (
  36. <button onClick={goTop} style={style}>
  37. Back to Top
  38. </button>
  39. );
  40. }

6、函数组件forceUpdate

  1. export function useForceUpdate() {
  2. const [, setState] = useState(0);
  3. const update = useCallback(() => {
  4. setState((prev) => prev + 1);
  5. }, []);
  6. return update;
  7. }
  8. const forceUpdate = useForceUpdate();
  9. // 或者
  10. const [, forceUpdate] = React.useReducer((x) => x + 1, 0);