javascript - 显示/隐藏按钮的条件渲染 - 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>
}
我不知道,我不明白我错在哪里。
解决方案
您已roles
在 state 中定义为长度为零的字符串。这意味着当您从渲染方法中的状态解构它时,它是定义的,而不是未定义的。这意味着您不能使用现有的三元检查,因为roles ? something : somethingelse
检查是否roles
已定义。
要更正此问题,请改为检查长度。roles
如果为零,则返回空按钮,否则显示活动按钮:
!roles.length ? showEmptyButton : showActiveButton
推荐阅读
- excel - Excel堆积条形图所需的数据结构
- mysql - 当我使用完全相同的查询定位不同的列时,查询不起作用
- python - 在这种情况下,这个 Python 的列表值赋值是如何工作的?
- node.js - 如何修复'错误:找不到模块'supertest''
- python - 如何修复opencv/modules/objdetect/src/cascadedetect.cpp:1698:错误:(-215:断言失败)!函数'detectMultiScale'^中的empty()?
- batch-file - 执行 bat 文件后获取不需要的文件
- r - R使用嵌套的for循环尾部扩展和处理数据
- r - t.test 在第三列上的特定代码之后的两列之间
- sql - 如何在spark上做一个sql连接?
- scala - 在scala中将字符串日期(不带分隔符)转换为日期格式