Json-sever GET 请求不断触发

时间:2021-03-05 14:07:20

标签: json reactjs api json-server

我在我的机器上本地设置了一个 json-server 用作我正在创建的应用程序的模拟 API。我在端口 3004 上运行服务器,而我的应用程序在端口 3000 上运行。应用程序按预期运行;但是,在检查运行服务器的终端时,我注意到每毫秒都在不断调用 GET 请求 - 见下图:

enter image description here

这是正常行为吗?根据我下面的代码,我希望 GET 请求只被调用一次。 GET 请求是 React 应用程序的一部分,在 useEffect 内部调用。

useEffect(() => {
    fetch('http://localhost:3004/invoices',
        {
            headers : { 
                'Content-Type': 'application/json',
                'Accept': 'application/json'
        },
    }
    )
    .then(function(response){
        return response.json();
    })
    .then(function(myJson){
        setData(myJson);
    })
    .catch((error) => {
        console.error("Error:", error);
      });
  });

1 个答案:

答案 0 :(得分:2)

您需要为 useEffect 添加一个依赖项,例如,如果您希望它仅在第一次渲染时触发,您可以这样写

useEffect(() => {
fetch('http://localhost:3004/invoices',
    {
        headers : { 
            'Content-Type': 'application/json',
            'Accept': 'application/json'
    },
}
)
.then(function(response){
    return response.json();
})
.then(function(myJson){
    setData(myJson);
})
.catch((error) => {
    console.error("Error:", error);
  });
},[]);

更有可能的是,您希望在发生变化时触发效果,在这种情况下,将依赖添加到方括号中...

useEffect(() => {
fetch('http://localhost:3004/invoices',
    {
        headers : { 
            'Content-Type': 'application/json',
            'Accept': 'application/json'
    },
}
)
.then(function(response){
    return response.json();
})
.then(function(myJson){
    setData(myJson);
})
.catch((error) => {
    console.error("Error:", error);
  });
},[someState]);
相关问题