【发布时间】:2020-04-19 09:45:07
【问题描述】:
在过去的 2-3 天里,我一直在为这个问题头疼。我正在尝试在加载新用户的帐户页面时显示新用户的 displayName 集并存储在 Firebase 身份验证数据库中。我似乎无法在第一次加载时显示它。我在 UserAccount 组件本身中尝试了 setState 方法,但它导致了同样的问题。需要手动刷新页面才能更改用户名状态以及 p 元素在屏幕中显示 displayName。请帮我解决这个问题。这是 UserAccount 组件的代码。如果您需要其他组件的其他代码,请告诉我。
class UserAccount extends React.Component {
constructor(props) {
super(props)
this.state = {
username: this.props.user.displayName
}
this.signout = this.signout.bind(this);
}
signout() {
firebase.auth().signOut()
}
The following commented code is my first try to get the displayName to show but it had the same issue so I tried to pass the props from the App.js component to see if it would work but it again has the same issue:
// componentDidMount () {
// firebase.auth().onAuthStateChanged((user) => {
// if (user) {
// var displayName = user.displayName;
// console.log(displayName);
// this.setState((state) => {
// return {username: displayName} })
// } else {
// console.log('Please sig in')
// }
// })
// }
render () {
return (
<div>
<h1> You are in </h1>
<button onClick={this.signout}>Sign Out</button>
<p>Hey {this.state.username}</p>
</div>
)
}
}
【问题讨论】:
标签: reactjs firebase authentication