Reactjs 第二次和第一次调用API时,React hooks useffect调用API响应也返回

Reactjs 第二次和第一次调用API时,React hooks useffect调用API响应也返回,reactjs,react-hooks,use-effect,Reactjs,React Hooks,Use Effect,我正在获取具有useEffect的API,API响应正确 {response: {message: "This is a image link", status: "success"}, error: null} 第二次,当我收到下一个API调用响应时,如果出现错误,则旧响应不会被删除。就像这样 {response: {message: "This is a image link", status: "success"}, error: TypeError} 我编写了获取API的教程代码 查

我正在获取具有useEffect的API,API响应正确

{response: {message: "This is a image link", status: "success"}, error: null}
第二次,当我收到下一个API调用响应时,如果出现错误,则旧响应不会被删除。就像这样

{response: {message: "This is a image link", status: "success"}, error: TypeError}
我编写了获取API的教程代码

查一下我的准确密码

import React,{useState}来自“React”;
从“react dom”导入react dom;
导入“/styles.css”;
const useFetch=(url,选项)=>{
console.log(“useFetch”);
const[response,setResponse]=React.useState(null);
const[error,setError]=React.useState(null);
React.useffect(()=>{
const FetchData=async()=>{
试一试{
const res=等待获取(url、选项);
const json=await res.json();
setResponse(json);
//log(“json-”,json);
}捕获(错误){
//log(“错误-”,错误);
设置错误(错误);
}
};
FetchData();
},[url]);
返回{响应,错误};
};
函数App(){
常量API_URL=`https://dog.ceo/api/breeds/image/random`;
const[apirl,setapirl]=useState(API_URL);
const res=useFetch(apirl,{});
console.log(“res-”,res);
如果(!res.response){
返回装载。。。;
}
常数apiCallAgain=()=>{
常量apiUrl=`https://d.ceo/api/breeds/image/q`;
setapirl(apirl);
};
const dogName=res.response.status;
const imageUrl=res.response.message;
返回(
应用程式介面呼叫
{dogName}
);
}
const rootElement=document.getElementById(“根”);
render(,rootElement);

打开控制台并默认选中
res
对象。现在单击
API调用
按钮,再次检查
res
对象。当我在启动中使用useState
null
时,为什么会显示旧状态?

当组件重新启动时,钩子不会重新初始化其中的所有状态。如果出现这种情况,状态将无法工作(更改状态时组件将重新呈现)

对于每个渲染,
useState
hook存储并返回该渲染的特定值。在您的例子中,当
API\u URL
更改时,
useffect
会重新运行,但状态变量不会

从:

这是一种在函数调用之间“保留”某些值的方法- useState是一种新的方法,可以使用与之完全相同的功能 此.state在类中提供。通常情况下,变量在 函数退出,但状态变量由React保留

解决方法是在
useffect
中重置响应和错误的状态:

 React.useEffect(() => {
    setResponse(null);
    setError(null);
    const FetchData = async () => {
      try {
        const res = await fetch(url, options);
        const json = await res.json();
        setResponse(json);
        // console.log("json - ", json);
      } catch (error) {
        // console.log("error - ", error);
        setError(error);
      }
    };
    FetchData();
  }, [url]);

请在此处添加相关代码,这样即使不使用第三方服务也可以解决此问题。我的实验表明,
setResponse(null)
setError(null)
不会被第二次调用。@Elye没有得到你的答案。。你能详细说明一下吗?我调用
useFetch(myUrl,option)
一次,它就工作了。第二次调用时,它不再工作,只返回相同的结果。我用错钩子了吗?
 React.useEffect(() => {
    setResponse(null);
    setError(null);
    const FetchData = async () => {
      try {
        const res = await fetch(url, options);
        const json = await res.json();
        setResponse(json);
        // console.log("json - ", json);
      } catch (error) {
        // console.log("error - ", error);
        setError(error);
      }
    };
    FetchData();
  }, [url]);