【问题标题】:Reactjs - array/iterator keyReactjs - 数组/迭代器键
【发布时间】:2017-02-09 14:30:55
【问题描述】:

我遇到以下错误:

warning.js?0260:45Warning: 数组或迭代器中的每个子元素都应该 有一个独特的“关键”道具。检查Tabs的渲染方法。

  render() {

    const { tabs } = this.props;
    const { active } = this.state;
    return (
      <div>
        <ButtonToolbar>
          {tabs.map(listValue =>
            <Button  onClick={() => this.handleClick(listValue)}>
              {listValue}
            </Button>
          )}
        </ButtonToolbar>

        // Display the chosen tab
        {this.showTab(active)}



      </div>
    );

在这种情况下,我应该在哪里添加 id 属性。我试过了:

<ButtonToolbar>
              {tabs.map(listValue =>
                <Button key={listValue.id}  onClick={() => this.handleClick(listValue)}>
                  {listValue}
                </Button>
              )}
            </ButtonToolbar>

但它并没有摆脱错误。请指教

【问题讨论】:

  • 如果你 console.log(listValue.id) 它们都是唯一的吗?
  • 你也可以tabs.map((listValue, index) =&gt; &lt;Button key={listValue.id + index} onClick={() =&gt; this.handleClick(listValue)}&gt; {listValue} &lt;/Button&gt; )}

标签: reactjs key


【解决方案1】:

您可以为此使用map 的迭代器:

<ButtonToolbar>
  {tabs.map((listValue, key) =>
    <Button              ^--- here
      key={key}   <--- and here.
      onClick={() => this.handleClick(listValue)}
    >
      {listValue}
    </Button>)
  }
</ButtonToolbar>

参考

【讨论】:

    猜你喜欢
    • 2020-09-28
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-30
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多