javascript - 为什么显示后无法清除错误消息-axios-react

标签 javascript reactjs react-hooks axios use-effect

First question for context

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

也想显示有关连接问题的消息 我尝试在 finally block 中添加 setError(""); 但错误消息停止工作。

如果我在收到错误时不添加这次工作,但当我修复错误时,错误仍然出现。

我想再次显示用户详细信息

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;

最佳答案

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

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

Codesandbox Demo


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;

关于javascript - 为什么显示后无法清除错误消息-axios-react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72930732/

相关文章:

javascript - 除非刷新,AngularJS 不会运行 Controller

javascript - 未捕获的类型错误 : Cannot read property 'call' of undefined' in backend. min.js:2

javascript - 通过 Props 将值从 React Stateless Child 传递给 Parent

javascript - 将对象值添加到 React 的 useMemo Hook

reactjs - 当依赖之一是来自 useContext 的函数时,useEffect 中的 InfiniteLoop

javascript - 克隆一个 DIV 并修改 ID

javascript - 我需要帮助理解 javascript ||。是否为逻辑 'OR'

javascript - 没有路线匹配位置 "/rewards-store"

javascript - 无法读取未定义的属性 'thisCompilation' - react-scripts-ts

javascript - 如何在 React 中更新我的帖子的评论