Javascript 在componentWillMount中设置状态时如何解决日志记录问题
我对状态有问题,因为我不是100%使用componentDidMount和componentWillMount 我已经设置了构造函数和超级道具,我正在使用getCurrentUser()方法获取一个用户对象,并使用新对象设置用户状态Javascript 在componentWillMount中设置状态时如何解决日志记录问题,javascript,reactjs,Javascript,Reactjs,我对状态有问题,因为我不是100%使用componentDidMount和componentWillMount 我已经设置了构造函数和超级道具,我正在使用getCurrentUser()方法获取一个用户对象,并使用新对象设置用户状态 componentWillMount() { const current_user = getCurrentUser().then(user => { this.setState({ user: user }); con
componentWillMount() {
const current_user = getCurrentUser().then(user => {
this.setState({
user: user
});
console.log(user);
});
}
componentDidMount() {
console.log(this.state.user);
}
它在componentWillMount中正确记录用户,但在componentDidMount中记录空对象
任何指导都将不胜感激
getCurrentUser
是一个异步方法,它调用另一个异步方法(setState
)
我很确定您将首先看到componentDidMount
中的日志条目,然后才看到componentWillMount
中的日志条目
正在发生的是:
componentWillMount
getCurrentUser
)组件将立即装载
返回,无需等待承诺完成componentDidMount
日志是由于方法的
异步性质造成的getCurrentUser
。在componentWillMount
中调用getCurrentUser
时,可能会在componentDidMount
完成执行后产生输出,因此您可以在componentDidMount
中看到初始状态。但是,console.log incomponentWillMount
位于getCurrentUser
中。然后承诺回调
,它将记录从getCurrentUser()
收到的当前值,但不要使用componentWillMount,
在componentDidMount中执行此操作
实际上,componentDidMount是放置调用以获取数据的最佳位置,原因有二:
使用DidMount可以清楚地表明,只有在初始渲染之后才会加载数据。这提醒您正确设置初始状态,这样您就不会得到导致错误的未定义状态
如果你需要在服务器上呈现你的应用程序(SSR/同构/其他流行语),componentWillMount实际上会被调用两次——一次在服务器上,一次在客户端——这可能不是你想要的。将数据加载代码放入componentDidMount将确保仅从客户端获取数据。您知道在调用componentDidMount
时承诺已返回吗?我将断点放在然后
函数和componentDidMount
中,然后看哪个先被击中这就是componentWillMount被弃用的确切原因。像这样被误用了很多次。谢谢你,真的很感谢你的解释!实际上,我正在将服务器渲染与Next.js一起使用,并且希望能够将用户状态作为道具传递给其他组件,以便像current_user={this.state.user}一样在其他组件中使用。如果componentDidMount需要等待页面首先呈现,是否可能?是。您可以在render方法中这样做:{this.state.user&&this.state.user!==undefined&&}确保组件仅在状态为ready时渲染。这很有意义,非常感谢!它开始融化我的大脑一点