简体   繁体   English

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

[英]Do not understand 400 error when using ComponentDidMount() - React Axios

Ok, so when I use ComponentDidUpdate() the get call works just fine, except for the fact that it infinite loops.好的,所以当我使用 ComponentDidUpdate() 时,get 调用工作得很好,除了它无限循环的事实。 When I use this code:当我使用这段代码时:

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

I keep getting the 400 error.我不断收到 400 错误。 Can anyone help me out with this, I am lost.谁能帮我解决这个问题,我迷路了。 Its a personal project and not homework before anyone asks.这是一个个人项目,而不是任何人问之前的家庭作业。

Try to move your async function outside of componentDidMount and call it from there.尝试将您的异步 function 移到 componentDidMount 之外并从那里调用它。 And it seems that you are also using a variable named part .而且您似乎还使用了一个名为part的变量。 You should also provide it to the function as well.您还应该将其提供给 function。 Since it is giving a 400 error, it must be something related to your parameters mostly coming from your state.由于它给出了 400 错误,它一定与您的参数有关,主要来自您的 state。

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

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

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