React - setState 不更新值 [英] React - setState does not update the value
本文介绍了React - setState 不更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 DidMount 中的 localStorage 值更新状态,但它没有更新:
I am trying to update the state with a localStorage value in DidMount, but it is not updating:
type Props = {
};
type State = {
id_evaluation: string,
};
class Evaluation extends Component < Props, State > {
state = {
id_evaluation: '',
}
componentDidMount() {
const id_eval = getEvaluation();
console.log('1 - ', id_eval)
this.setState({
id_evaluation: '1',
});
console.log('2 - ', this.state.id_evaluation)
在第一个 console.log 中,我的值为 1,在第二个中它保持为空,不更新状态.
In the first console.log I have the value 1, in the second it remains empty, it does not update the state.
推荐答案
this.setState 是一个异步函数.
this.setState is an async function.
this.setState({
id_evaluation: '1',
}, () => console.log('2 - ', this.state.id_evaluation));
回调函数可以解决您的问题.
Callback function would solve your problem.
这篇关于React - setState 不更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文