当前位置:首页 > React

react如何控制loading状态

2026-03-31 12:29:37React

控制 Loading 状态的方法

在 React 中,可以通过多种方式控制 loading 状态,以下是常见的实现方法:

使用 useState 管理状态 通过 useState 钩子定义一个布尔值状态变量,用于表示 loading 的状态。

import { useState } from 'react';

function MyComponent() {
  const [isLoading, setIsLoading] = useState(false);

  const fetchData = async () => {
    setIsLoading(true);
    try {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div>
      {isLoading ? <div>Loading...</div> : <button onClick={fetchData}>Load Data</button>}
    </div>
  );
}

使用自定义 Hook 可以封装一个自定义 Hook 来复用 loading 逻辑。

function useLoading() {
  const [isLoading, setIsLoading] = useState(false);

  const startLoading = () => setIsLoading(true);
  const stopLoading = () => setIsLoading(false);

  return { isLoading, startLoading, stopLoading };
}

function MyComponent() {
  const { isLoading, startLoading, stopLoading } = useLoading();

  const fetchData = async () => {
    startLoading();
    try {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
    } catch (error) {
      console.error(error);
    } finally {
      stopLoading();
    }
  };
}

结合 Context API 如果需要在多个组件间共享 loading 状态,可以使用 Context API。

import { createContext, useContext, useState } from 'react';

const LoadingContext = createContext();

function LoadingProvider({ children }) {
  const [isLoading, setIsLoading] = useState(false);

  const value = { isLoading, setIsLoading };
  return <LoadingContext.Provider value={value}>{children}</LoadingContext.Provider>;
}

function useLoadingContext() {
  return useContext(LoadingContext);
}

function MyComponent() {
  const { isLoading, setIsLoading } = useLoadingContext();

  const fetchData = async () => {
    setIsLoading(true);
    try {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };
}

使用第三方库 一些第三方库(如 react-queryswr)内置了 loading 状态管理功能。

import { useQuery } from 'react-query';

function MyComponent() {
  const { isLoading, data } = useQuery('fetchData', () =>
    fetch('https://api.example.com/data').then(res => res.json())
  );

  return isLoading ? <div>Loading...</div> : <div>{data}</div>;
}

优化用户体验

添加延迟加载 为了避免闪烁,可以设置一个最小 loading 时间。

const fetchData = async () => {
  const startTime = Date.now();
  setIsLoading(true);
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    const elapsedTime = Date.now() - startTime;
    if (elapsedTime < 500) {
      await new Promise(resolve => setTimeout(resolve, 500 - elapsedTime));
    }
  } catch (error) {
    console.error(error);
  } finally {
    setIsLoading(false);
  }
};

使用动画或骨架屏 替换简单的 "Loading..." 文本,提升用户体验。

react如何控制loading状态

import { Skeleton } from 'antd';

function MyComponent() {
  const [isLoading, setIsLoading] = useState(false);

  return (
    <div>
      {isLoading ? (
        <Skeleton active />
      ) : (
        <button onClick={() => setIsLoading(true)}>Load Data</button>
      )}
    </div>
  );
}

注意事项

  • 确保在 finally 块中重置 loading 状态,避免因错误导致状态卡住。
  • 对于复杂的应用,考虑使用状态管理库(如 Redux)集中管理 loading 状态。
  • 避免过度使用 loading 状态,仅在必要操作时显示。

标签: 状态react
分享给朋友:

相关文章

vue实现订单状态

vue实现订单状态

vue实现订单状态 在Vue中实现订单状态管理,通常需要结合组件设计、状态管理和后端交互。以下是常见的实现方法: 数据定义与状态枚举 // 订单状态常量定义 const ORDER_STATUS…

如何降低react版本

如何降低react版本

降低 React 项目版本的步骤 检查当前 React 版本 运行以下命令查看项目中安装的 React 当前版本: npm list react 或 yarn list react 修改…

如何运行react

如何运行react

运行 React 项目的步骤 安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过官网 Node.js 下载并安装最新稳定版本。安装完成后,验证版本: node…

如何安装react

如何安装react

安装React的方法 方法一:使用Create React App(官方推荐) Create React App是官方提供的脚手架工具,适合快速搭建React项目。确保已安装Node.js(建议版本≥…

如何调试react

如何调试react

调试 React 应用的方法 使用 React Developer Tools 安装浏览器扩展(Chrome/Firefox),通过组件树查看组件状态、props 和 hooks。支持实时编辑 pro…

小白如何搭建react

小白如何搭建react

安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过官网下载安装包(https://nodejs.org/),选择 LTS 版本。安装完成后,终端运行以下命令验证版…