gpt4 book ai didi

javascript - 在构造函数类中调用函数

转载 作者:行者123 更新时间:2023-11-30 14:35:38 27 4
gpt4 key购买 nike

我试图在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com