【问题标题】:React rendering based on boolean in state: ternary not working基于状态布尔值的反应渲染:三元不工作
【发布时间】:2020-12-10 19:24:15
【问题描述】:

React Dev Tools 显示状态正在成功更改,但是正确的组件没有呈现。

这是切换状态的按钮内的三元组:

return (
  <div>
    <div>{questionBlocks}</div>
    <button className="advanced-options" onClick={this.toggleAdvanced}>
      {this.state.advancedText}
      <span>
        {this.showAdvanced ? <ExpandLessIcon /> : <ExpandMoreIcon />}
      </span>
    </button>
  </div>
);

这里是 toggleAdvanced 功能(效果很好,因为我在切换 showAdvanced 时成功展示了新元素:

toggleAdvanced = (e) => {
    e.preventDefault();
    if (this.state.showAdvanced === true) {
      this.setState((prevState) => ({
        showAdvanced: !prevState.showAdvanced,
      }));
    } else {
     this.setState((prevState) => ({
       showAdvanced: !prevState.showAdvanced,
      }));
    }
};

查看了thesesolutions等,但没有成功。

【问题讨论】:

    标签: javascript reactjs state conditional-operator


    【解决方案1】:

    您在三元组中缺少state。应该是this.state.showAdvanced,而不是this.showAdvanced

    【讨论】:

      【解决方案2】:

      问题可能就在这里

        <span>
              {this.showAdvanced ? <ExpandLessIcon /> : <ExpandMoreIcon />}
            </span>
      

      您使用的是this.showAdvanced,但它应该是this.state.showAdvanced

      【讨论】:

        猜你喜欢
        • 2021-08-03
        • 2021-12-14
        • 2021-09-23
        • 2021-10-22
        • 2021-11-20
        • 1970-01-01
        • 2020-10-19
        • 2018-12-03
        • 2021-01-17
        相关资源
        最近更新 更多