reactjs - 是否可以在 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
})
})
})
}
解决方案
我认为在点击处理程序中使用它是可以的。并且不要忘记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
})
})
})
}
推荐阅读
- mysql - 从mysql到mongo db的数据调度问题
- javascript - 如何在javascript中从sql中使用power函数?
- java-8 - Anypoint Studio 启动/部署问题
- selenium - 我们在哪里可以找到我们在 Selenium 的 Chrome 功能中使用的首选项名称(键)?
- android - 全屏TextInputEditText不显示计数器
- javascript - 如何防止Enter按钮操作onSubmit?
- odoo - 在编辑模式下打开弹出表单
- php - 如何使用 sql 获取特定记录?
- django - pip3 不在我的环境中全局安装 django
- javascript - Pixabay API HTTP重定向和混合内容错误