【问题标题】:Async function call repeated inside of class component在类组件内部重复异步函数调用
【发布时间】:2021-11-25 02:15:40
【问题描述】:

我创建了一个异步函数来调用天气 API,该 API 将返回所提交的请求信息。该函数工作正常,但是当我在类组件中调用此函数时,结果会返回两次。这并不是一个严重的错误,但如果没有必要,我宁愿不发生两次 API 调用,我很好奇为什么这个方法首先被调用两次。

这是我的代码。


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>;
};

【问题讨论】:

    标签: javascript reactjs asynchronous promise


    【解决方案1】:

    问题是您在WeatherCard 的渲染方法中调用getResults,将其移至useEffect,因此不会每次都调用它

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

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 2017-04-07
      • 2023-03-25
      • 2018-11-17
      • 2023-03-22
      • 2011-02-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      相关资源
      最近更新 更多