React:我可以在渲染之前检查状态是否存在
问题描述:
我是 React 的新手,我制作了一个显示用户名 user 的导航栏
I'm new to React and I've made a navbar that displays the users name user
<NavItem eventKey={4} href="#">{this.state.name}</NavItem>
但问题是如果用户未登录,我会因为 this.state.name 未定义而收到错误消息.在将 this.state.name 渲染为导航栏的一部分之前,有什么方法可以检查它是否已定义,或者是否有更好的方法来消除此错误?
but the problem is if the user is not signed in, I get an error due to this.state.name being undefined. Is there some way I can check if this.state.name is defined before rendering it as part of the navbar or is there a better way to get rid of this error?
答
当然,使用三元:
render() {
return (
this.state.name ? <NavItem>{this.state.name}</NavItem> : null
);
}
甚至更短
render() {
return (
this.state.name && <NavItem>{this.state.name}</NavItem>
);
}