首页 > 解决方案 > 基于布尔值的反应渲染状态:三元不工作

问题描述

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,
      }));
    }
};

看了这些 解决方案,除其他外,但没有成功。

标签: javascriptreactjsstateconditional-operator

解决方案


问题可能就在这里

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

您正在使用this.showAdvanced,但应该是this.state.showAdvanced


推荐阅读