【发布时间】:2019-01-21 12:45:33
【问题描述】:
我遇到了状态问题,因为我不是 100% 正确使用 componentDidMount 和 componentWillMount。
我已经设置了构造函数和超级道具,我正在使用 getCurrentUser() 方法获取用户对象并使用新对象设置用户状态。
componentWillMount() {
const current_user = getCurrentUser().then(user => {
this.setState({
user: user
});
console.log(user);
});
}
componentDidMount() {
console.log(this.state.user);
}
它在 componentWillMount 中正确记录用户,但在 componentDidMount 中记录一个空对象。
任何指导将不胜感激!
【问题讨论】:
-
你知道在调用
componentDidMount时promise 已经返回了吗?我会在then函数和componentDidMount中放置断点,看看哪个被首先击中 -
这就是 componentWillMount 被弃用的确切原因。大多数时候它都被滥用了。
标签: javascript reactjs