React.js点击按钮处理数据时如何显示加载屏并跳转结果页

实现方案
针对你使用React+FastAPI+MongoDB的技术栈,需要实现点击Estimate按钮先展示加载页、处理完成后跳转结果页的需求,按前后端拆分实现即可:
1. 前端React侧实现
- 提前配置3个路由:信息提交页(含Estimate按钮)、加载中转页、结果展示页
- 给Estimate按钮绑定点击事件:点击后先校验用户上传的信息格式,校验通过后将表单数据存入
sessionStorage(避免刷新丢失),直接跳转到加载中转页 - 加载页内置加载动画,在组件的
useEffect钩子中发起估算请求到FastAPI接口 - 请求成功拿到返回结果后,将结果存入
sessionStorage供结果页读取,再跳转到结果展示页;请求失败则弹出错误提示,2秒后自动跳转回提交页
核心代码示例:
// 加载页核心逻辑,基于react-router v6实现 import { useEffect, useState } from 'react' import { useNavigate } from 'react-router-dom' const EstimateLoading = () => { const [error, setError] = useState('') const navigate = useNavigate() useEffect(() => { // 读取之前存储的用户提交数据 const rawForm = sessionStorage.getItem('estimateFormData') if (!rawForm) { navigate('/submit') return } const formData = JSON.parse(rawForm) const getEstimateResult = async () => { try { const res = await fetch('/api/estimate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(formData) }) const result = await res.json() sessionStorage.setItem('estimateResult', JSON.stringify(result)) navigate('/result') } catch (e) { setError('估算处理失败,请稍后重试') setTimeout(() => navigate('/submit'), 2000) } } getEstimateResult() }, [navigate]) return ( <div className="loading-container"> {error ? <p style={{ color: 'red' }}>{error}</p> : <p>正在进行估算,请稍候...</p>} {/* 此处可替换为你的自定义加载动画组件 */} </div> ) }
2. 后端FastAPI侧适配
- 先配置CORS跨域中间件,避免前端跨域请求报错,生产环境严格限制允许的前端域名即可
- 按业务需求实现估算接口:接收前端传来的表单数据,操作MongoDB完成业务逻辑处理后返回结果
- 如果单请求处理耗时超过30秒,建议改成后台任务+轮询的方案:接口收到请求后先返回唯一任务ID,将计算任务丢到后台异步执行,前端每隔3-5秒用任务ID查询处理状态,查询到处理完成后再跳转结果页,避免网关超时导致请求失败
核心代码示例:
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import pymongo import asyncio app = FastAPI() # 配置跨域 app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000"], # 替换为你的前端实际地址 allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # 连接MongoDB mongo_client = pymongo.MongoClient("mongodb://localhost:27017/") db = mongo_client["your_database_name"] # 定义请求参数结构 class EstimateForm(BaseModel): # 按你实际的表单字段补充即可 info: str user_id: str @app.post("/api/estimate") async def handle_estimate(form: EstimateForm): # 你的业务处理逻辑,此处模拟3秒耗时 await asyncio.sleep(3) # 操作MongoDB的代码自行补充 # 返回估算结果 return { "status": "success", "data": { "estimate_value": 15600, # 补充其他返回字段 } }
内容的提问来源于stack exchange,提问作者Asma Alghamdi
相关产品推荐
相关产品推荐

