首页 > 解决方案 > 在数组中“推送” JSX 元素时反应变量评估

问题描述

我在数组中推送 JSX 元素

for (category of this.state.categories) {
  categories.push(
    <li>
      <label 
        className="tree-toggler nav-header list-group-item" 
        onClick={() => this.showHideConnectorNames(category)}
      >
        {category}
      </label>
      <ul 
        className="tree ul-no-style" 
        id={category+'Connectors'}
      >
      </ul>
    </li>
  );
}

问题是方法调用中的category变量评估为数组中的最后一个(因此所有元素都是“cat2”)。它在所有其他地方都被正确评估,例如在.this.showHideConnectorNames(category)categorythis.state.categories<label>

所以我必须这样做:

for (category of this.state.categories) {
  if (category === 'cat1')
    categories.push(
      <li>
        <label 
          className="tree-toggler nav-header list-group-item" 
          onClick={() => this.showHideConnectorNames('cat1')}
        >
          {category}
        </label>
        <ul 
          className="tree ul-no-style" 
          id={category + 'Connectors'}
        >
        </ul>
      </li>
    ); 
  else if (category === 'cat2')
    categories.push(
      <li>
        <label 
          className="tree-toggler nav-header list-group-item" 
          onClick={() => this.showHideConnectorNames('cat2')}
        >
          {category}
        </label>
        <ul 
          className="tree ul-no-style" 
          id={category + 'Connectors'}
        >
        </ul>
      </li>
    );
  else
    categories.push(
      <li>
        <label 
          className="tree-toggler nav-header list-group-item" 
          onClick={() => this.showHideConnectorNames(category)}
        >
          {category}
        </label>
        <ul 
          className="tree ul-no-style" 
          id={category + 'Connectors'}
        >
        </ul>
      </li>
    );
}

这是一个 React 问题还是我做错了什么?

标签: javascriptreactjs

解决方案


不确定构建后要对数组做什么,但我认为使用map调用会更有效率。只需将其放在您要呈现列表项的任何地方的 return 语句中:

<ul>
  {this.state.categories.map(cat => (
    // your li has a missing key property
    <li>
      <label
        className="tree-toggler nav-header list-group-item"
        onClick={() => this.showHideConnectorNames(cat)}
      >
        {cat}
      </label>
      <ul
        className="tree ul-no-style"
        id={cat + 'Connectors'}
      ></ul>
    </li>
  ))}
</ul>

推荐阅读