在尝试从函数更新状态并从componentdidmount生命周期方法调用函数时,状态不会更新。但是当我尝试通过从 jsx 内部调用函数来更新状态时,它确实有效。我不知道发生了什么
//my state
constructor(){
super()
this.state = {
activepage:'dashboard',
language:[],
}
}
//the function I am updating state from
getLanguage = () => {
axios.get('http://localhost:3001/language')
.then(function (response) {
console.log(response.data.language);
this.setState({
language:response.data.language
})
})
.catch(function (error) {
return error;
});
}
//I am calling function from
componentDidMount(){
this.getLanguage();
console.log("state after updating",this.state) //displays an empty array
}
但是当我getLanguage从 jsx 内部调用函数时,它会更新状态。