簡體   English   中英

顯示/隱藏按鈕的條件渲染 - ReactJs

[英]Conditional rendering of showing / hiding a button - ReactJs

我試圖隱藏菜單按鈕,如果有的話。 如果用戶不被允許看到菜單,我會從令牌中收到一個空的rol(基本上是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定義為零長度字符串。 這意味着當您從render方法中的狀態對其進行解構時,它是定義的,而不是未定義的。 意味着您不能使用現有的三元檢查,因為roles ? something : somethingelse roles ? something : somethingelse檢查是否定義了 roles

要更正此問題,請檢查roles長度 如果為零則返回空按鈕,否則顯示活動按鈕:

!roles.length ? showEmptyButton : showActiveButton

首先,確保使用setState()更新組件的roles狀態。 對於組件,您可以在componentDidMount()生命周期鈎子中執行此操作:

/* Remove async from method signature as it's not needed */
componentDidMount() {
  const base64Url = token.split('.')[1];
  const decodedValue = JSON.parse(window.atob(base64Url))
  const roles = decodedValue.roles;

  /* Very important - this will trigger a re-render for your
  component which will ensure that the subsequent render is
  done so with the updated roles state in effect */
  this.setState({ roles : roles });
}

接下來,您需要確保基於條件角色的條件渲染基於組件roles狀態的布爾重新執行。 據我所知,如果roles狀態為''['']則會顯示空角色按鈕:

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

    /* If roles is falsey, or first element of roles array 
    is falsey then show empty button */       
    const isEmptyRole = !roles || !roles[0];

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM