我的状态有问题,因为我不是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中。
任何指导将不胜感激!
答案 0 :(得分:3)
getCurrentUser
是一个异步方法,它调用了另一个异步方法(setState
)。
我非常确定您将首先看到componentDidMount
的日志条目,然后才看到componentWillMount
的日志条目。
正在发生的事情:
componentWillMount
getCurrentUser
)componentWillMount
立即返回,而无需等待承诺完成componentDidMount
答案 1 :(得分:3)
根本不使用componentWillMount, 在componentDidMount中完成。
实际上,有两个原因,componentDidMount是放置调用以获取数据的最佳位置:
使用DidMount可以清楚地表明,只有在初始渲染之后才会加载数据。这提醒您正确设置初始状态,以免最终导致出现错误的未定义状态。
如果您需要在服务器上渲染应用程序(SSR /同构/其他流行语),componentWillMount实际上将被调用两次-一次在服务器上,再一次在客户端上-这可能不是您想要的。将数据加载代码放入componentDidMount中将确保仅从客户端获取数据。
答案 2 :(得分:1)
该日志归因于您的方法asynchronous
的{{1}}性质。当您在getCurrentUser
中调用getCurrentUser
时,可能会在componentWillMount
执行完毕后产生输出,因此您会在componentDidMount
中看到初始状态。但是componentDidMount
中的console.log位于componentWillMount
getCurrentUser
中,它将记录从.then promise callback