我想在页面的左侧显示记录的使用名称。 当我尝试到达用户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);
答案 0 :(得分:1)
在您的代码中,this.state.user
直到componentDidMount()
之后才是真值,直到第一个渲染之后才生效。在初始渲染期间,您尝试访问的对象中尚不存在的值。
您可以做的是实施一个条件来检查this.state.user
是否有效,否则显示一个空字符串。组件重新渲染的速度非常快,因此您甚至不会注意到first-render上的空字符串。
<Header style={{ padding: "0.25em" }} as="h4" inverted>
<Dropdown
trigger={<span>{this.state.user ? this.state.user.displayName : ""}</span>}
options={this.dropdownOptions()}
/>
</Header>