将道具传递给组件Didmount道具、组件、Didmount

2023-09-03 12:40:12 作者:安然

能够在我的仪表板组件中呈现道具,但无法将其传递给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进程发送电子邮件值。 应该是在控制台中收到电子邮件,但我得到的却是"未定义"。

推荐答案

发生在您身上的唯一情况是email从某个异步调用开始。事情是这样发生的:

emailundefined状态。但是您进行了一个异步调用来获取email。 呈现组件,但emailundefined,因为异步调用尚未完成,因此您在componentDidMount中控制undefined。 然后,您将从异步调用(电子邮件的setState)中获得结果,它将转到道具,并使用正确的电子邮件重新呈现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
  }
}