You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS表单提交时Loading Indicator不生效问题求助

问题解决:表单提交时加载指示器不显示

核心问题分析

你的代码里有两个关键问题导致加载指示器无法正常工作:

  • 提交函数未正确处理异步逻辑,setIsLoading(false)在模拟的2秒延迟完成前就执行了,导致加载状态瞬间结束
  • Chakra UI的Button组件未绑定isLoading状态,无法触发内置的加载指示器

具体修改步骤

  1. 修正提交函数的异步逻辑
    将提交函数改为异步函数,用await等待模拟的异步操作,确保加载状态持续2秒:

    const onSubmit = async (data) => {
      setIsLoading(true);
      // 模拟2秒的异步请求(比如接口调用)
      await new Promise(resolve => setTimeout(resolve, 2000));
      console.log("表单数据:", data);
      setIsLoading(false);
    };
    
  2. 给Button绑定加载状态
    在Button组件上添加isLoading属性,关联你的状态变量,同时可自定义加载提示文本:

    <Button
      type="submit"
      colorScheme="blue"
      isLoading={isLoading}
      loadingText="提交中"
    >
      提交
    </Button>
    
  3. 确认状态初始化正确
    确保组件顶部已正确初始化加载状态:

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

完整修改后的关键代码片段

import { useState } from "react";
import { useForm } from "react-hook-form";
import { Box, FormControl, FormLabel, Input, Button, VStack } from "@chakra-ui/react";

export default function App() {
  const [isLoading, setIsLoading] = useState(false);
  const { register, handleSubmit } = useForm();

  const onSubmit = async (data) => {
    setIsLoading(true);
    await new Promise(resolve => setTimeout(resolve, 2000));
    console.log(data);
    setIsLoading(false);
  };

  return (
    <Box p={4}>
      <VStack spacing={4} as="form" onSubmit={handleSubmit(onSubmit)}>
        <FormControl isRequired>
          <FormLabel>用户名</FormLabel>
          <Input {...register("username")} placeholder="请输入用户名" />
        </FormControl>
        <Button
          type="submit"
          colorScheme="blue"
          isLoading={isLoading}
          loadingText="提交中"
        >
          提交
        </Button>
      </VStack>
    </Box>
  );
}

修改后,点击提交按钮时,按钮会自动显示加载指示器并禁用,2秒后恢复正常,同时控制台会打印表单数据。

内容的提问来源于stack exchange,提问作者nuser137

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 21:02:14