【问题标题】:Do not understand 400 error when using ComponentDidMount() - React Axios使用 ComponentDidMount() 时不理解 400 错误 - React Axios
【发布时间】:2020-08-31 13:48:18
【问题描述】:

好的,所以当我使用 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 错误。谁能帮我解决这个问题,我迷路了。这是一个个人项目,在任何人询问之前都不是家庭作业。

【问题讨论】:

  • 你的控制台输出什么?有什么错误吗?还有,不应该是exclude=${part}吗?
  • 400 表示错误请求。需要更多信息来回答这个问题。
  • 您应该检查开发者控制台的网络部分以查看您发送到服务器的请求。可能您的某些变量未定义,这就是您从服务器收到错误请求的原因。

标签: javascript reactjs axios


【解决方案1】:

尝试将您的异步函数移到 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');
  }

【讨论】:

  • 好的,这给了我修复。我将函数移到组件的类声明中。但是我在调​​用地理位置 api 回调函数时调用了它。这样它就有了纬度和经度。谢谢诺斯特罗莫!
猜你喜欢
  • 1970-01-01
  • 2020-05-24
  • 2022-01-17
  • 1970-01-01
  • 1970-01-01
  • 2022-11-26
  • 2017-11-27
  • 2021-07-21
  • 1970-01-01
相关资源
最近更新 更多