简体   繁体   English

异步 function 调用在 class 组件内部重复

[英]Async function call repeated inside of class component

I've created an Asynchronous function to call a weather API that will return the requested information submitted.我创建了一个异步 function 来调用天气 API ,它将返回提交的请求信息。 The function works fine however when I call this function inside of a Class Component the result is returned twice. function 工作正常,但是当我在 Class 组件内部调用此 function 时,结果将返回两次。 This isn't exactly a breaking bug but I'd rather not have two API calls occurring if not necessary and I'm curious as to why this method is being called twice in the first place.这并不是一个严重的错误,但如果没有必要,我宁愿不要发生两次 API 调用,我很好奇为什么这个方法首先被调用两次。

Here is my code.这是我的代码。


async function submitQuery(props) {
  //Incase I decide to add aditional parameters such as city, country etc.. I've decided to place the zip property in an object so I can just
  //add additional properties in the submissions object
  const submission = {
    zip: props,
  };

  if (!Number(props)) return console.log("this is not a number");

  const { error } = await validate(submission);
  if (error) return console.log(error.message);

  const config = {
    method: "get",
    url: `https://api.openweathermap.org/data/2.5/weather?zip=${props}&appid=${apiKey}`,
    headers: {},
  };

  /*
  const query = await axios(config).then(function (response) {
    const result = response.data.main;
    return result;
  });
  */

  //console.log(query);
  return 4;
}
class WeatherReport extends React.Component {
  getResults = async () => {
    const result = await submitQuery("08060");
    console.log(result);
  };

  render() {
    return (
      <div className="reportContainer">
        <WeatherCard getResults={this.getResults} />
      </div>
    );
  }
}

const WeatherCard = ({ getResults }) => {
  getResults();
  return <div></div>;
};

The problem is that you're calling getResults in the render method of WeatherCard , move it to a useEffect so its not called every time问题是您在WeatherCard的 render 方法中调用getResults ,将其移至useEffect ,因此不会每次都调用它

const WeatherCard = ({ getResults }) => {
    React.useEffect(() => {
        getResults();
    }, [getResults]);
    return <div></div>;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM