【问题标题】:How to fix logging issues when setting state in componentWillMount在 componentWillMount 中设置状态时如何解决日志记录问题
【发布时间】: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


【解决方案1】:

根本不要使用componentWillMount, 在 componentDidMount 中执行。

实际上,componentDidMount 是调用获取数据的最佳位置,原因有两个:

使用 DidMount 可以清楚地表明在初始渲染之前不会加载数据。这会提醒您正确设置初始状态,这样您就不会出现导致错误的未定义状态。

如果您需要在服务器上渲染您的应用程序(SSR/同构/其他流行语),componentWillMount 实际上会被调用两次——一次在服务器上,一次在客户端上——这可能不是你想要的。将数据加载代码放在 componentDidMount 中将确保只从客户端获取数据。

【讨论】:

  • 谢谢你,非常感谢你的解释!我实际上是在使用 Next.js 的服务器渲染,并希望能够将用户状态作为道具传递给其他组件,例如 current_user={this.state.user}。如果componentDidMount需要等待页面先渲染,这可能吗?
  • 是的。您可以在渲染方法中这样做:
    {this.state.user && this.state.user!==undefined && }
    确保组件仅在状态就绪时渲染
  • 嗯,有道理,非常感谢!它开始让我的大脑有点融化
【解决方案2】:

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

我很确定您会首先看到来自componentDidMount 的日志条目,然后才会看到来自componentWillMount 的日志条目。

发生了什么:

  1. 响应调用componentWillMount
  2. 您开始异步调用 (getCurrentUser)
  3. componentWillMount 立即返回,无需等待承诺完成
  4. 响应调用componentDidMount
  5. 你的承诺解决了

【讨论】:

    【解决方案3】:

    这些日志是由于您的方法getCurrentUserasynchronous 特性造成的。当您在componentWillMount 中调用getCurrentUser 时,可能会在componentDidMount 完成执行后导致输出,因此您会在componentDidMount 中看到初始状态。但是componentWillMount 中的console.log 位于getCurrentUser .then promise callback 中,它将记录从getCurrentUser() 收到的当前值

    【讨论】:

      猜你喜欢
      • 2020-12-14
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      • 2012-01-12
      • 2020-08-30
      • 2019-11-25
      • 1970-01-01
      相关资源
      最近更新 更多