将道具传递给componentDidMount

时间:2019-04-29 13:29:13

标签: reactjs react-props

能够在Dashboard组件中渲染道具,无法将其传递给componentDidMount进行进一步的Ajax处理。

渲染工作正常并显示信息。

我正在使用Firebase,并且工作正常。

App.js

// React core.
import React, { Component } from 'react';
import Dashboard from './components/Dashboard';

class App extends Component {

 //firebase...

  state = {
    isSignedIn: undefined,
    displayName: undefined,
    email: undefined
  };

  componentDidMount() {

      this.setState({providerData: user.providerData}) 
      this.setState({ displayName: user.providerData[0].displayName })  
      this.setState({ email: user.providerData[0].email })   
    });
  }

  render() {
    return (

      <div className={styles.container}>
        {this.state.isSignedIn !== undefined && !this.state.isSignedIn &&
          //Not signed-in yet
          <div>

            <Login />

          </div>
        }

        {this.state.isSignedIn &&
          //Signed in
          <div>
            <Dashboard 
              displayName={this.state.displayName} 
              email={this.state.email} />

          </div>
        }   
      </div>
    );
  }
}

export default App;

Dashboard.js

import React, { Component } from 'react';


class Dashboard extends Component {


    componentDidMount() {
        var thisComponent = this
        console.log(thisComponent.props.email)
    }

    render()  {
        const email = this.props.email

        return (
            <div>
                <h1>Hello, {this.props.displayName}!</h1>
                <h2>Your email is: {email}</h2> 
            </div>
        );
    }
}

export default Dashboard;

Dashboard.js中的componentDidMount是让我震惊的原因。无法发送电子邮件值以进行进一步的ajax处理。 应该在控制台中获取电子邮件,相反,我收到“未定义”消息。

enter image description here

1 个答案:

答案 0 :(得分:2)

唯一可能发生的情况是email来自某个异步调用。这是怎么回事:

  1. emailundefined状态。但是您进行异步调用以获取email
  2. 您渲染了组件,但是emailundefined,因为异步调用尚未完成,因此您在undefined中管理componentDidMount
  3. 然后您从异步调用(电子邮件的setState)中得到结果,该结果将变为prop,然后使用正确的电子邮件重新发送Dashboard

这样,您会看到呈现的电子邮件,但是在componentDidMount中电子邮件是未定义的。它已经渲染了2次,仅在几秒钟的时间内,就已经安装了组件,您将获得正确的email

这是唯一可以看到数据的情况,但是componentDidMount中没有定义数据,我几乎可以确定这是您的情况。

您几乎没有提供解决问题的代码,而我唯一能做的就是通过对案例进行一些假设来为您提供问题的原因。希望这可以帮助您理解并解决问题。

编辑:在您的代码中,您正在使用firebase(异步调用)来接收电子邮件,因此我的假设是正确的,现在只需要知道预期的结果即可。

编辑: 如果您需要对组件内部的电子邮件进行某些操作,请使用componentDidMount

对于您的情况,您可以

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.email != undefined && this.props.email !== prevProps.email) {
    // Do what you want with email
  }
}