【发布时间】:2019-10-07 19:53:08
【问题描述】:
我想在页面左侧显示记录的用户名。 当我尝试访问用户 displayName 时,它说它无法找到未定义的值。有人可以解释我为什么吗?
我尝试了componentDidMount和其他一些方法,但是这里渲染的时候好像有问题
componentDidMount() {
firebase.auth().onAuthStateChanged(user => {
// If firebase has detect a user
if (user) {
this.props.setUser(user);
this.props.history.push("/");
这是文件
class UserPanel extends React.Component {
state = {
user: null
}
componentDidMount(){
this.setState({ user: this.props.currentUser })
}
dropdownOptions = () => [
{
key: "user",
text: (
<span>
Sign in as <strong>{this.state.user && this.state.user.displayName}</strong>
</span>
),
disabled: true
},
{
key: "avatar",
text: <span>Change Avatar</span>
},
{
key: "signout",
// Set a signout Function to enable user to sign out of the chat
text: <span onClick={event => this.handleSignOut(event)}>SignOut</span>
}
];
handleSignOut = (event) => {
// You need to prevent form submission. Use event.preventDefault() in your handle submit function.
event.preventDefault();
firebase
.auth()
.signOut()
.then(() => console.log("See you"));
}
render(){
console.log(this.props.currentUser);
// !this.state.currentUser ? <Spinner /> :
return (
<Grid style={{ background: '#4c3c4c' }}>
<Grid.Column>
<Grid.Row style={{ padding: '1.2rem', margin: 0 }}>
<Header inverted floated='left' as='h2'>
<Icon name='code' />
<Header.Content>VirtualChat</Header.Content>
</Header>
</Grid.Row>
{/* User Dropdown Choices */}
<Header style={{ padding: "0.25em" }} as="h4" inverted>
<Dropdown
trigger={<span>{this.state.user.displayName}</span>}
options={this.dropdownOptions()}
/>
</Header>
</Grid.Column>
</Grid>
)
}
}
const mapStateToProps = state => ({
currentUser: state.user.currentUser
})
export default connect(mapStateToProps)(UserPanel);
【问题讨论】:
标签: reactjs firebase-authentication undefined render