使用ComponentDidMount()时不理解400错误-React Axios

时间:2020-08-31 13:48:18

标签: javascript reactjs axios

好,所以当我使用ComponentDidUpdate()时,get调用工作得很好,除了它无限循环。当我使用此代码时:

componentDidMount() {

        const getRequest = async() => {
            try {
                const result = await axios.get(`https://api.openweathermap.org/data/2.5/onecall?lat=${this.state.lat}&lon=${this.state.long}&
                exclude={part}&appid=${this.state.apikey}&units=imperial`);

                console.log(result);
            }
            catch(err){
                console.error(err);
            }
        }

        getRequest();
}

我不断收到400错误。谁能帮我这个忙,我迷路了。这是一个个人项目,而不是在任何人问之前都不做作业。

1 个答案:

答案 0 :(得分:2)

尝试将异步功能移到componentDidMount之外,然后从那里调用它。 似乎您也在使用一个名为 part 的变量。您还应该将其提供给函数。 因为它给出了400错误,所以它一定是与您的参数相关的东西,主要来自您的状态。

  getRequest = async (apikey, lat, long, part) => {           
    try {
        const result = await axios.get(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${long}&
        exclude={part}&appid=${apikey}&units=imperial`);
        console.log(result);
    }
    catch(err){
        console.error(err);
    }
  }

  componentDidMount() {
    const { apikey, lat, long } = this.state;
    this.getRequest(apikey, lat, long, 'daily');
  }