【问题标题】:Warning: Each child in a list should have a unique "key" prop. Key prop doesn't show when inspect element警告:列表中的每个孩子都应该有一个唯一的“关键”道具。检查元素时不显示关键道具
【发布时间】:2019-06-07 23:23:42
【问题描述】:

我的ListItem.js看起来像这样:

render() {
        return(
            <li key={parseInt(this.props.keyProp)}>
                <button onClick={this.props.onClick} 
                    className="sidebar__button">
                        {this.props.text}
                </button>
            </li>
        );
    }

当我单独放置 {parseInt(this.props.keyProp)} 时,它会显示一个数字。 但是当我将它等同于 &lt;li&gt; 的 key 属性时,我收到错误 Warning: Each child in a list should have a unique "key" prop. 并且当我检查 &lt;li&gt; 上的元素时我也看不到任何键。

我正在分享使用ListItem.js的代码

populateLi = () => {
        let LIs = []
        for (var keyItem in graphs) {
            if (graphs.hasOwnProperty(keyItem)) {
                LIs.push(<ListItem keyProp={keyItem} onClick={this.onClick} text={graphs[keyItem][0]["Scheme Name"]}/>)
            }
        }
        return LIs;
    }

【问题讨论】:

  • this.props.keyProp的值是多少?
  • stackoverflow.com/questions/33682774/… 简而言之,key 用于在后台进行反应以优化性能。查看我发布的stackoverflow链接中的第二个答案
  • 确保 parseInt(this.props.keyProp) 确实返回一个值,并且确实为每个列表项返回不同的值。
  • 你为什么使用parseInt? React 期望键是 string,而不是数字。如果parseInt 接收到非数字值,则返回 NaN。这很可能是您收到该警告的原因。
  • 是的,key 应该是一个字符串。即使我删除 parseInt,问题仍然存在

标签: javascript reactjs


【解决方案1】:

key 属性应该添加到负责渲染ListItem.js 的函数中。所以:

items.map((item) =&gt; KeyItem key={item.id} item={item} /&gt;

【讨论】:

    【解决方案2】:

    根据 react 文档,“key”属性是一个特殊的 string 属性,用于优化和识别。它不会出现在 HTML 中。

    您遇到的错误是由于每个列表元素没有唯一键。这应该通过为每个元素分配一个唯一的键来解决。

    更多信息在这里: https://reactjs.org/docs/lists-and-keys.html

    【讨论】:

      【解决方案3】:

      密钥应该是 ListItem 本身而不是 ListItem 内的 &lt;li&gt;

      LIs.push(<ListItem key={keyItem} onClick={this.onClick} text={graphs[keyItem][0]["Scheme Name"]}/>)
      

      这解决了问题。

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 2019-08-04
        • 2021-01-12
        • 2022-06-28
        • 2021-09-01
        • 2019-12-05
        • 2021-09-05
        • 2020-03-01
        • 1970-01-01
        相关资源
        最近更新 更多