能够在我的仪表板组件中呈现道具,但无法将其传递给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
从某个异步调用开始。事情是这样发生的:
email
为undefined
状态。但是您进行了一个异步调用来获取email
。
呈现组件,但email
是undefined
,因为异步调用尚未完成,因此您在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
}
}