React中如何在Axios HTTP请求后展示提示弹窗?
实现请求成功/错误弹窗提示
直接修改你的AddColor.js代码,添加弹窗状态管理和Axios请求的回调处理即可,以下是完整修改后的代码:
import axios from "axios" import { useState } from "react"; export default function AddColor() { const [Name, setcolorName] = useState(''); // 管理弹窗状态:是否显示、类型(success/error)、提示消息 const [alert, setAlert] = useState({ show: false, type: '', message: '' }); const handleSubmit = (e) => { e.preventDefault(); axios({ method: 'post', url: 'http://localhost:64082/api/color/add', data: { Name } }) // 请求成功的回调 .then(() => { // 显示成功弹窗 setAlert({ show: true, type: 'success', message: '颜色添加成功!' }); // 清空输入框 setcolorName(''); // 可选:3秒后自动关闭弹窗 setTimeout(() => setAlert({...alert, show: false}), 3000); }) // 请求失败的回调 .catch(error => { // 显示错误弹窗,可根据实际错误信息调整消息 setAlert({ show: true, type: 'error', message: `添加失败:${error.response?.data?.message || '网络异常'}` }); // 可选:3秒后自动关闭弹窗 setTimeout(() => setAlert({...alert, show: false}), 3000); }) } // 手动关闭弹窗的方法 const closeAlert = () => { setAlert({...alert, show: false}); } return ( <div className="create"> <h2>Add a New Color</h2> {/* 弹窗组件:条件渲染 */} {alert.show && ( <div className={`alert alert-${alert.type}`} style={{ padding: '10px', marginBottom: '15px', borderRadius: '4px', backgroundColor: alert.type === 'success' ? '#d4edda' : '#f8d7da', color: alert.type === 'success' ? '#155724' : '#721c24', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}> <span>{alert.message}</span> <button onClick={closeAlert} style={{ background: 'none', border: 'none', fontSize: '18px', cursor: 'pointer' }}>×</button> </div> )} <form onSubmit={handleSubmit}> <label>color Name:</label> <input type="text" required value={Name} placeholder="please enter color name..." onChange={(e) => setcolorName(e.target.value)} /> <button>Add Color</button> </form> </div> ) }
关键修改点说明:
- 新增
alert状态变量,用来控制弹窗的显示状态、类型和提示内容 - 在Axios请求的
.then()回调中处理成功逻辑:显示成功弹窗、清空输入框,可选添加自动关闭功能 - 在
.catch()回调中处理错误逻辑:捕获请求异常,显示对应的错误提示 - 添加条件渲染的弹窗组件,根据
alert.type设置不同的样式,同时支持手动关闭 - 修正了按钮文字(原按钮写的是"Add Category",应该是"Add Color")
你可以直接复制这段代码替换原文件,也可以根据自己的样式需求调整弹窗的CSS样式。
内容的提问来源于stack exchange,提问作者NewPartizal
相关产品推荐
相关产品推荐

