尝试从函数更新状态并从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 内部调用函数时,它会更新状态。
用 es6 箭头函数更新你的函数
.then((response) => {
console.log(response.data.language);
this.setState({
language:response.data.language
})
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句