在componentWillMount中设置状态时如何解决日志记录问题

时间:2019-01-21 12:45:34

标签: javascript reactjs

我的状态有问题,因为我不是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中。

任何指导将不胜感激!

3 个答案:

答案 0 :(得分:3)

getCurrentUser是一个异步方法,它调用了另一个异步方法(setState)。

我非常确定您将首先看到componentDidMount的日志条目,然后才看到componentWillMount的日志条目。

正在发生的事情:

  1. 响应呼叫componentWillMount
  2. 您发起异步呼叫(getCurrentUser
  3. componentWillMount立即返回,而无需等待承诺完成
  4. 响应呼叫componentDidMount
  5. 您的诺言兑现

答案 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

收到的当前值。