首页 > 解决方案 > 如何以最简洁的方式处理错误和成功响应?

问题描述

如何以最简洁的方式显示服务器响应错误或成功消息?现在,我正在使用异步函数发出 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.');
    }
  });
};

标签: reactjsreact-reduxreact-router

解决方案


希望这是你想要的

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));
};

推荐阅读