【发布时间】:2018-12-28 11:22:33
【问题描述】:
在尝试从函数更新状态并从 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
}
但是当我从 jsx 内部调用函数 getLanguage 时,它会更新状态。
【问题讨论】:
-
当您更新
state时,它不会立即更新。您可以使用setState回调来查看状态何时更新。看到这个:stackoverflow.com/a/50604716/4089357 -
你用反应开发工具检查,而不是控制台,这里也是
-
谢谢你。它成功了