簡體   English   中英

警告:列表中的每個孩子都應該有一個唯一的“關鍵”道具。 檢查元素時不顯示關鍵道具

[英]Warning: Each child in a list should have a unique “key” prop. Key prop doesn't show when inspect element

我的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)}時,它會顯示一個數字。 但是,當我將其等同於<li> key屬性時,會收到錯誤Warning: Each child in a list should have a unique "key" prop. 而且當我檢查<li>上的元素時,我也看不到任何鍵。

我正在共享使用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;
    }

key道具應添加到負責渲染ListItem.js的函數中。 所以:

items.map((item) => KeyItem key={item.id} item={item} />

根據反應文檔,“鍵”道具是特殊的字符串屬性,用於優化和識別。 它不會出現在HTML中。

您收到的錯誤是由於每個列表元素都沒有唯一鍵。 應該通過為每個元素分配唯一鍵來解決此問題。

此處提供更多信息: https : //reactjs.org/docs/lists-and-keys.html

鍵應該是ListItem本身,不在ListItem內的<li>

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

這解決了問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM