首页 > 解决方案 > 是否可以在 componentDidMount 以外的任何方法中使用 axios get 方法?

问题描述

我正在使用 axios 在 React js 中开发 Weather App。我在 handleClick 方法中使用 axios get 方法。这样使用是否可以。这里我删除了应用程序密钥,但我在我的项目中使用它。

handleClick=()=>
    {
      this.setState({isClicked:true},()=>{
        const url = `https://api.openweathermap.org/data/2.5/weather?q=${this.state.city}&cnt=${this.state.country}&appid=appKey`;
          axios.get(url).then((resp)=>
          {
            this.setState({
              temperature:resp.data.main.temp
            })
          })
        })
    }

标签: reactjsreact-lifecycle

解决方案


我认为在点击处理程序中使用它是可以的。并且不要忘记isClicked再次设置为false,如果它用于防止双击:

handleClick=()=>
    {
      this.setState({isClicked:true},()=>{
        const url = `https://api.openweathermap.org/data/2.5/weather?q=${this.state.city}&cnt=${this.state.country}&appid=appKey`;
          axios.get(url).then((resp)=>
          {
            this.setState({
              temperature:resp.data.main.temp,
            })
          }).finally(() => {
            this.setState({
              isClicked: false
            })
          })
        })
    }


推荐阅读