我试图在 FiveDayWeather 类的构造函数中调用 getWeather()。我将函数绑定(bind)到类的上下文,但是当我尝试在构造函数中调用函数时,它出错了。
我试过:
this.getWeather()
当这不起作用时:
getWeather()
但这也没有用
如何从此类内部调用 getWeather 函数?
class FiveDayWeather extends React.Component {
constructor(props) {
super(props)
this.state = {
error: null,
isLoaded: false,
days: []
}
this.getWeather = this.getWeather.bind(this)
getWeather()
console.log(this.state);
}
getWeather() {
axios.get(URL)
.then(function(response) {
this.setState({
days: response
})
})
}
render() {
return(
<div>Placeholder</div>
)
}
}
这不是关于从异步调用返回响应
最佳答案
根据您的说明:
I am trying to call the getWeather() inside of the constructor
它不会在构造函数中工作。将它放在 componentDidMount()
生命周期方法中,比如
componentDidMount(){
this.getWeather();
}
根据您在下方的评论,像这样更新 promise :
getWeather() {
axios.get(URL)
.then((response) => {
this.setState({
days: response
})
})
}
箭头函数应该为你绑定(bind)this
的上下文
关于javascript - 在构造函数类中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50474209/