【问题标题】:How to handle multiple errors in React?如何处理 React 中的多个错误?
【发布时间】:2021-09-22 10:27:01
【问题描述】:

在我的 React 应用程序中,我创建了以下 NoteDetail 组件。我的问题是:处理多个error 变量的最佳实践是什么,在这种情况下,我可能从我的GET API 请求中获得一个,另一个从我的DELETE API 请求中获得?我想到的第一个解决方案是使用专用的getErrordeleteError 变量,但我不知道这是否是推荐的处理方法。

import { Link, useParams } from "react-router-dom";
import useFetch from "./useFetch";
import { api } from "./api";
import axios from "axios";

const NoteDetail = () => {
  const { id } = useParams();
  const { data: note, error, loading } = useFetch(api.notes.retrieve(id));
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleClick = () => {
    axios
      .delete(api.notes.delete(id))
      .then((response) => {
        setLoading(false);
        history.pushState("/");
      })
      .catch((error) => {
        setLoading(false);
        setError(error.message || error);
      });
  };

  return (
    <div className="note-details">
      {loading && <div>Loading...</div>}
      {error && <div>{error}</div>}
      {note && (
        <article>
          <h2>{note.title}</h2>
          <p>Written by {note.author}</p>
          <div>{note.body}</div>
          <Link to={"/update/" + note.id}>
            <button>Edit</button>
          </Link>
          <button onClick={handleClick}>Delete</button>
        </article>
      )}
    </div>
  );
};

export default NoteDetail;

【问题讨论】:

    标签: reactjs api error-handling


    【解决方案1】:

    根据文档,最好的方法是 Error Boundaries 概念。

    错误边界是捕捉 JavaScript 错误的 React 组件 在其子组件树中的任何位置,记录这些错误并显示 一个后备 UI,而不是崩溃的组件树。

    如果类组件定义了一个名为 componentDidCatch(error, info) 的新生命周期方法,则该类组件将成为错误边界:

    class ErrorBoundary extends React.Component {
      constructor(props) {
        super(props);
        this.state = { hasError: false };
      }
    
      componentDidCatch(error, info) {
        // Display fallback UI
        this.setState({ hasError: true });
        // You can also log the error to an error reporting service
        logErrorToMyService(error, info);
      }
    
      render() {
        if (this.state.hasError) {
          // You can render any custom fallback UI
          return <h1>Something went wrong.</h1>;
        }
        return this.props.children;
      }
    }
    

    然后你可以用这个ErrorBoundary 组件来包装你的其他组件,如下所示:

    <ErrorBoundary>
      <MyWidget />
    </ErrorBoundary>
    

    请记住,错误边界只会捕获树中它们下方组件中的错误。

    LIVE DEMO

    【讨论】:

      猜你喜欢
      • 2010-09-23
      • 2021-01-09
      • 2022-11-22
      • 2022-01-03
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多