ReactJS表单提交时Loading Indicator不生效问题求助
问题解决:表单提交时加载指示器不显示
核心问题分析
你的代码里有两个关键问题导致加载指示器无法正常工作:
- 提交函数未正确处理异步逻辑,
setIsLoading(false)在模拟的2秒延迟完成前就执行了,导致加载状态瞬间结束 - Chakra UI的Button组件未绑定
isLoading状态,无法触发内置的加载指示器
具体修改步骤
修正提交函数的异步逻辑
将提交函数改为异步函数,用await等待模拟的异步操作,确保加载状态持续2秒:const onSubmit = async (data) => { setIsLoading(true); // 模拟2秒的异步请求(比如接口调用) await new Promise(resolve => setTimeout(resolve, 2000)); console.log("表单数据:", data); setIsLoading(false); };给Button绑定加载状态
在Button组件上添加isLoading属性,关联你的状态变量,同时可自定义加载提示文本:<Button type="submit" colorScheme="blue" isLoading={isLoading} loadingText="提交中" > 提交 </Button>确认状态初始化正确
确保组件顶部已正确初始化加载状态: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
相关产品推荐
相关产品推荐

