Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在componentWillMount中设置状态时如何解决日志记录问题_Javascript_Reactjs - Fatal编程技术网

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

Javascript 在componentWillMount中设置状态时如何解决日志记录问题,javascript,reactjs,Javascript,Reactjs,我对状态有问题,因为我不是100%使用componentDidMount和componentWillMount 我已经设置了构造函数和超级道具,我正在使用getCurrentUser()方法获取一个用户对象,并使用新对象设置用户状态 componentWillMount() { const current_user = getCurrentUser().then(user => { this.setState({ user: user }); con

我对状态有问题,因为我不是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中记录空对象


任何指导都将不胜感激

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

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

正在发生的是:

  • React调用
    componentWillMount
  • 启动异步调用(
    getCurrentUser
  • 组件将立即装载
    返回,无需等待承诺完成
  • React调用
    componentDidMount
  • 你的诺言解决了

  • 日志是由于方法的
    异步
    性质造成的
    getCurrentUser
    。在
    componentWillMount
    中调用
    getCurrentUser
    时,可能会在
    componentDidMount
    完成执行后产生输出,因此您可以在
    componentDidMount
    中看到初始状态。但是,console.log in
    componentWillMount
    位于
    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时渲染。这很有意义,非常感谢!它开始融化我的大脑一点