简体   繁体   中英

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

My ListItem.js looks like this:

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

When I separately place {parseInt(this.props.keyProp)}, it shows a number. But when I equate it to key property of the <li> , I get the error Warning: Each child in a list should have a unique "key" prop. and I also cannot see any key when I inspect element on the <li> .

I am sharing the code which uses 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;
    }

The key prop should be added to the function that is responsible for rendering ListItem.js . So:

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

As per the react documentation, the "key" prop is a special string attribute that is used for optimization and identification. It does not appear in the HTML.

The error you are getting is due to the fact that each list element does not have a unique key. This should be fixed by assigning a unique key to each element.

More info here: https://reactjs.org/docs/lists-and-keys.html

The key is supposed to be ListItem itself not on the <li> inside ListItem

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

That fixes the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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