首页 > 解决方案 > 显示/隐藏按钮的条件渲染 - ReactJs

问题描述

如果有,我正在尝试隐藏菜单按钮。Baiscly,如果不允许用户查看菜单,我会从令牌中收到一个空角色(基本上rol : [''] ,否则如果允许的话rol : ['_DECLARATION']。我已经尝试过条件渲染,但也许我弄错了我使用的方法。如果有人能伸出援手就好了。

 constructor(props) {
        super(props);
        this.state = {
                roles: '' 
                     }

async componentDidMount() {
const base64Url = token.split('.')[1];
const decodedValue = JSON.parse(window.atob(base64Url))
const roles = decodedValue.roles;

 render() {
 const { roles } = this.state
    return (

        { roles 
        ? <Button className="emptyRollButtonDec"/>
        : <Button
          onClick={this.changeActiveComponent
          style= {{
              background: branding.color.colorPrimary,
              color: branding.color.colorTextPrimary
                  }}>
           Declaration
           </Button>
         }

我不知道,我不明白我错在哪里。

标签: javascriptreactjsjsx

解决方案


您已roles在 state 中定义为长度为零的字符串。这意味着当您从渲染方法中的状态解构它时,它是定义的,而不是未定义的。意味着您不能使用现有的三元检查,因为roles ? something : somethingelse检查是否roles定义

要更正此问题,请改为检查长度。roles如果为零,则返回空按钮,否则显示活动按钮:

!roles.length ? showEmptyButton : showActiveButton

推荐阅读