api react js中openweathermap的key

api key of openweathermap in react js

我在 React 中使用 openweathermap(免费帐户)的 API 编写了一个天气应用程序。我已经像这样在 componentDidMount 中使用了 fetch。

async componentDidMount()
  {
    const url1 = "https://api.openweathermap.org/data/2.5/weather?units=metric&q=Hanoi,VN&appid=" + api_key;
    const today = await GetData(url1);
    const url2 = "https://api.openweathermap.org/data/2.5/forecast?units=metric&q=Hanoi,VN&appid=" + api_key;
    const forecast = await GetData(url2);
    this.setState({
      data: today,
      forecast: forecast
    });

考虑到我的 API 密钥已被阻止一次,因为它在一分钟内用于超过 60 个请求。因此我有一个问题,如果有人在我的网页上重新加载垃圾邮件,

  1. 它会在每次重新加载时调用 componentDidMount 吗?
  2. 我怎样才能避免这种情况?

每次重新加载页面时都会调用componentDidMount。

关于组件生命周期方法的详细内容请阅读官方文档https://reactjs.org/docs/react-component.html#the-component-lifecycle。我认为您无法阻止 componentDidMount 在页面重新加载时被调用。因为这就是它的工作原理。

但是,您可以从您的服务器调用 openweatherapp 并使用基于 IP 的节流来防止对您的服务器的 DoS 攻击。