reactjs - 如何以最简洁的方式处理错误和成功响应?
问题描述
如何以最简洁的方式显示服务器响应错误或成功消息?现在,我正在使用异步函数发出 axios 请求,并且在成功/错误时我只是更新本地状态(使用 react-hook-form),但我觉得它“丑陋”,我希望页面尽可能干净,并将代码在后台处理服务请求中的成功和错误消息。
例子 :
忘记密码.jsx
import React, { useState } from 'react';
import Layout from '../components/core/Layout';
import axios from 'axios';
import { useForm } from 'react-hook-form';
import { Button, Form, Alert } from 'react-bootstrap';
import { regex } from '../constants';
import { isAuth } from '../helpers';
import { forgotPassword } from '../services/User';
import { Redirect } from 'react-router-dom';
const Forgot = () => {
const {
handleSubmit,
register,
errors,
getValues,
setError,
setValue,
clearError
} = useForm({
mode: 'onBlur'
});
register({ name: 'responseError' });
register({ name: 'responseSuccess' });
const { responseSuccess } = getValues();
const onSubmit = async values => {
try {
const response = await forgotPassword(values);
setValue([{ responseSuccess: response.data.message }]);
// set response success msg to local state responseSuccess
} catch (error) {
setError('responseError', '', error);
// set response error msg to local state responseError
}
};
const forgotPasswordForm = () => (
<>
<Form onSubmit={handleSubmit(onSubmit)}>
<Form.Group>
<Form.Label>Email address</Form.Label>
<Form.Control
name='email'
ref={register({
required: true,
pattern: {
value: regex.email,
message: 'Invalid email address'
}
})}
type='email'
placeholder='Enter email'
isInvalid={errors.email}
/>
<Form.Control.Feedback type={errors.email ? 'invalid' : 'valid'}>
{errors.email && errors.email.message}
</Form.Control.Feedback>
</Form.Group>
<Button variant='primary' type='submit'>
Submit
</Button>
</Form>
<br />
{errors.responseError && (
<Alert
variant='danger'
dismissible
onClose={() => clearError('responseError')}>
{errors.responseError.message}
</Alert>
)}
</>
);
const forgotPasswordFormSuccess = () => (
<Alert
variant='success'
className='mt-5'
dismissible
onClose={() => setValue([{ responseSuccess: '' }])}>
{responseSuccess}
</Alert>
);
if (isAuth()) return <Redirect to='/' />;
return (
<Layout>
<div>
<h1>Forgot password</h1>
{responseSuccess ? forgotPasswordFormSuccess() : forgotPasswordForm()}
</div>
</Layout>
);
};
export default Forgot;
忘记密码功能
export const forgotPassword = async ({ email }) => {
return new Promise(async (resolve, reject) => {
try {
const response = await Axios({
method: 'PUT',
url: `${process.env.REACT_APP_API}/forgot-password`,
data: { email }
});
resolve(response);
} catch (error) {
if (error.response) {
reject(error.response && error.response.data.error);
}
reject('Something went wrong. please try again later.');
}
});
};
解决方案
希望这是你想要的
export const forgotPassword = ({ email }) => {
return new Promise((resolve, reject) => {
axios(`${process.env.REACT_APP_API}/forgot-password`, {
method: 'PUT',
data: { email }
})
.then(res => resolve(res.data))
.catch(err => reject(err))
});
};
const onSubmit = values => {
forgotPassword(values)
.then(res => setValue([{ responseSuccess: res.message }]))
.catch(err => setError('responseError', '', err));
};
推荐阅读
- javascript - RNDateTimePicker 将日期格式从 MM/dd/yy 更改为其他任何内容
- c - /bin/sh: 1: aarch64-vtlinux-linux-g++ --sysroot=/opt/vtlinux/sysroots/aarch64-vtlinux-linux: 未找到
- javascript - 尝试更新时空加载日期 - Yii2
- python - Matplotlib 在图像上画线并设置轴 val
- azure - AADSTS50196:服务器终止操作,因为它在 azure 函数中遇到客户端请求循环
- sql - 无法设置 Percent_rank() - 默认为 0.0
- swift - Realm (Swift):迁移期间如何获取 MutableSet 数据?
- view - 雪花的物化视图
- ios - 用多行更改 UIMenu 标题(带有 UIButton 的 UIMenu)
- chef-infra - 在厨师食谱中编写循环的最佳实践是什么?