如何在Material-UI TextField下方展示API调用错误并实现重请求与输入校验
实现方案
核心逻辑说明
- 用3个状态变量分别管控:输入框内容
inputValue、输入校验错误状态inputError、API请求错误状态apiError - 输入框失焦/提交时先做非空校验,为空直接触发输入错误提示
- 校验通过后发起API请求,请求失败时把
apiError设为true,直到请求成功才重置为false - 错误提示文案里的「重新加载?」绑定点击事件,点击后复用当前输入内容重新触发API请求逻辑
完整代码示例(React + MUI v5)
import { useState } from 'react'; import { TextField, Typography, Box } from '@mui/material'; const ApiTextField = () => { const [inputValue, setInputValue] = useState(''); const [inputError, setInputError] = useState(false); const [apiError, setApiError] = useState(false); const [loading, setLoading] = useState(false); // 实际使用替换为真实接口调用 const requestApi = async (params) => { return new Promise((resolve, reject) => { setTimeout(() => { // 模拟随机请求失败 Math.random() > 0.5 ? resolve({ code: 200, data: 'success' }) : reject(new Error('请求失败')); }, 800); }) } const handleRequest = async () => { // 非空校验 if (!inputValue.trim()) { setInputError(true); return; } setInputError(false); setLoading(true); try { const res = await requestApi(inputValue); // 此处可扩展返回值合法性校验,不合法直接抛出错误即可触发提示 if (res.code !== 200) throw new Error('返回值不合法'); setApiError(false); // 后续业务逻辑 } catch (err) { setApiError(true); } finally { setLoading(false); } } const handleInputChange = (e) => { setInputValue(e.target.value); inputError && setInputError(false); } return ( <Box sx={{ width: 320, padding: 2 }}> <TextField label="请输入内容" variant="outlined" fullWidth value={inputValue} onChange={handleInputChange} error={inputError || apiError} disabled={loading} helperText={ inputError ? '输入内容不能为空' : apiError ? ( <Typography component="span" variant="body2"> Something went wrong! <span onClick={handleRequest} style={{ color: '#1976d2', cursor: 'pointer', textDecoration: 'underline' }} > Reload? </span> </Typography> ) : '' } {/* 可根据需求替换为绑定提交按钮的点击事件 */} onBlur={handleRequest} /> </Box> ) } export default ApiTextField;
功能验证点
- 输入为空时失焦/提交直接触发输入错误提示,输入内容后自动消失
- API请求失败后始终显示错误提示,点击
Reload?即可重新发起请求,请求成功后提示自动隐藏 - 可自行在代码预留位置扩展返回值合法性校验规则,不符合规则的返回值也会触发错误提示
内容的提问来源于stack exchange,提问作者mahdi mohammadi
相关产品推荐
相关产品推荐

