代码之家  ›  专栏  ›  技术社区  ›  Selcukusu

为什么在show-axios-react之后无法清除错误消息

  •  2
  • Selcukusu  · 技术社区  · 2 年前

    First question for context

    我正在显示使用 localhost:3000/users/:id API有10个用户,因此如果请求 localhost:3000/users/11 应显示错误消息

    还想显示连接问题的消息 我试图添加 setError(""); 在…内 finally 阻止,但错误消息停止工作。

    如果我没有添加这个时间工作时,我得到错误,但当我修复错误错误错误仍然出现。

    import { useParams } from "react-router-dom";
    import { useState, useEffect } from "react";
    import axios from "axios";
    
    function User() {
      const { id } = useParams();
      const [user, setUser] = useState(null);
      const [error, setError] = useState("");
      const [isLoading, setIsLoading] = useState(true);
    
      useEffect(() => {
        axios("https://jsonplaceholder.typicode.com/users/" + id)
          .then((res) => setUser(res.data))
          .catch((error) => setError(error.message))
          .finally(() => setIsLoading(false));
      }, [id]);
      return (
        <div>
          {error === "Request failed with status code 404" ? (
            <p>{error}</p>
          ) : isLoading ? (
            <h2>Loading...</h2>
          ) : (
            <div>
              <h3>User Info</h3>
              <p>Name: {user.name}</p>
              <p>Email: {user.email}</p>
              <p>Phone: {user.phone}</p>
            </div>
          )}
        </div>
      );
    }
    
    export default User;
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   dippas    2 年前

    当响应正常时,您必须清除错误

    .then((res) => {
       setUser(res.data);
       setError("")
    })
    

    这是一个 Sandbox

    ----
    
    import { useParams } from "react-router-dom";
    import { useState, useEffect } from "react";
    import axios from "axios";
    
    function User() {
      const { id } = useParams();
      const [user, setUser] = useState(null);
      const [error, setError] = useState("");
      const [isLoading, setIsLoading] = useState(true);
    
      useEffect(() => {
        axios("https://jsonplaceholder.typicode.com/users/" + id)
          .then((res) => {
            setUser(res.data);
            setError("")
          })
          .catch((error) => setError(error.message))
          .finally(() => setIsLoading(false));
      }, [id]);
      return (
        <div>
          {error === "Request failed with status code 404" ? (
            <p>{error}</p>
          ) : isLoading ? (
            <h2>Loading...</h2>
          ) : (
            <div>
              <h3>User Info</h3>
              <p>Name: {user.name}</p>
              <p>Email: {user.email}</p>
              <p>Phone: {user.phone}</p>
            </div>
          )}
        </div>
      );
    }
    
    export default User;