React:我可以在渲染之前检查状态是否存在 [英] React: Can I check if a state exists before rendering it

查看:39
本文介绍了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>
  );
}

这篇关于React:我可以在渲染之前检查状态是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆