简体   繁体   English

基于 state 中的 boolean 的反应渲染:三元不工作

[英]React rendering based on boolean in state: ternary not working

React Dev Tools shows me that the state is successfully changing, however the correct component is not rendering. React 开发工具向我显示 state 正在成功更改,但是正确的组件未呈现。

Here's the ternary inside a button that toggles state:这是切换 state 的按钮内的三元组:

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

Here's the toggleAdvanced function (that's working perfectly, as I am successfully showing new elements on toggling showAdvanced:这是 toggleAdvanced function(效果很好,因为我在切换 showAdvanced 时成功展示了新元素:

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

Looked at these solutions , amongst others, but no success.看了这些解决方案,除其他外,但没有成功。

the problem is probably here问题可能就在这里

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

You are using this.showAdvanced but it should be this.state.showAdvanced您正在使用this.showAdvanced但它应该是this.state.showAdvanced

You're missing state in the ternary.您在三元组中缺少state It should be this.state.showAdvanced , not this.showAdvanced .应该是this.state.showAdvanced ,而不是this.showAdvanced

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM