【问题标题】:Json-sever GET requests keep firingJson-server GET 请求不断触发
【发布时间】:2021-06-04 05:16:12
【问题描述】:

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

这是正常行为吗?根据下面的代码,我希望 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);
      });
  });

【问题讨论】:

  • 你应该添加一个依赖数组到useEffect。像这样传递空数组:useEffect(() => {}, [])。空数组意味着 - 在挂载时只执行一次。

标签: json reactjs api json-server


【解决方案1】:

你需要为你的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]);

【讨论】:

    猜你喜欢
    • 2016-05-05
    • 2012-09-16
    • 2021-07-12
    • 2017-06-28
    • 1970-01-01
    • 2021-08-04
    • 2020-04-15
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多