将道具传递给 componentDidMount

passing props to componentDidMount

能够在我的 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 进程发送电子邮件值。 应该在控制台中收到电子邮件,相反,我收到 "undefined".

唯一可能发生在您身上的情况是 email 来自某个异步调用。事情是这样发生的:

  1. emailundefined 状态。但是您进行异步调用以获取 email.
  2. 你渲染了组件,但是 emailundefined 因为异步调用还没有完成,所以你在 componentDidMount.[=44 中控制 undefined =]
  3. 然后你从异步调用中得到结果,电子邮件的 setState,它下降到 props 并重新呈现 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
  }
}