新手使用React :: 警告:列表中的每个子元素都应该有一个唯一的 “key” 属性

huangapple go评论85阅读模式
英文:

New to React :: Warning: Each child in a list should have a unique "key" prop

问题

以下是翻译好的部分:

"Very new to React and I keep getting the warning above. Have tried various methods to fix it, but had no luck, code is where I'm up to now. Probably something very simple, but I just cannot see it. I'm not running React through NodeJs and it's working apart from this warning."

BuildList.js 文件

const ListItem = props => {
    return (
        <li key={`${props.title}${props.index}`} className="my-list" onClick={props.onDelete}>
            {props.title}
        </li>
    )
}

class BuildList extends React.Component {

    constructor(props) {
        super(props);
        this.state = {items: props.data};
    }

    addItemHandler() {
        this.setState(prevState => {
            var newItem = prompt("Enter some text");

            if(newItem) {
                return {items: prevState.items.concat(newItem)};
            }
        });
    }

    deleteItemHandler(txt) {
        this.setState(prevState => {
            if(confirm('Are you sure?')) {
                return {items: prevState.items.filter(item => {
                        return item !== txt;
                    }
                )};
            }
        });
    }

    render() {
        return (
            <div>
                <p style={{'fontWeight': '700'}}>{this.props.intro}</p>
                <ul className="list-unstyled">
                    {this.state.items.map((item, index) => {
                        return (
                            <ListItem key={item} title={item} onDelete={this.deleteItemHandler.bind(this, item)} />
                        )
                    })}
                </ul>
                <button onClick={this.addItemHandler.bind(this)} className="btn btn-sm btn-success">Add</button>
            </div>
        )
    }
}

app.js 文件

(function(){

    //Defaults
    const domContainer = document.querySelector('#root');

    //Final output
    ReactDOM.render(
        [
            <BuildList data={['Item 1','Item 2', 'Item 3', 'Item 4']} intro="My first React list" />,             
        ], domContainer);
})()

以下是完整的警告信息:

react-dom.development.js:524 警告:列表中的每个子项都应具有唯一的 "key" 属性。更多信息请参见网站链接。
英文:

Very new to React and I keep getting the warning above. Have tried various methods to fix it, but had no luck, code is where I'm up to now. Probably something very simple, but I just cannot see it. I'm not running React through NodeJs and it's working apart from this warning.

BuildList.js file

    const ListItem = props =&gt; {
return (
&lt;li key={`${props.title}${props.index}`} className=&quot;my-list&quot; onClick={props.onDelete}&gt;
{props.title}
&lt;/li&gt;
)
}
class BuildList extends React.Component {
constructor(props) {
super(props);
this.state = {items: props.data};
}
addItemHandler() {
this.setState(prevState =&gt; {
var newItem = prompt(&quot;Enter some text&quot;);
if(newItem) {
return {items: prevState.items.concat(newItem)};
}
});
}
deleteItemHandler(txt) {
this.setState(prevState =&gt; {
if(confirm(&#39;Are you sure?&#39;)) {
return {items: prevState.items.filter(item =&gt; {
return item !== txt;
}
)};
}
});
}
render() {
return (
&lt;div&gt;
&lt;p style={{&#39;fontWeight&#39;: &#39;700&#39;}}&gt;{this.props.intro}&lt;/p&gt;
&lt;ul className=&quot;list-unstyled&quot;&gt;
{this.state.items.map((item, index) =&gt; {
return (
&lt;ListItem key={item} title={item} onDelete={this.deleteItemHandler.bind(this, item)} /&gt;
)
})}
&lt;/ul&gt;
&lt;button onClick={this.addItemHandler.bind(this)} className=&quot;btn btn-sm btn-success&quot;&gt;Add&lt;/button&gt;
&lt;/div&gt;
)
}
}

app.js file

(function(){
//Defaults
const domContainer = document.querySelector(&#39;#root&#39;);
//Final output
ReactDOM.render(
[
&lt;BuildList data = {[&#39;Item 1&#39;,&#39;Item 2&#39;, &#39;Item 3&#39;, &#39;Item 4&#39;]} intro=&quot;My first React list&quot; /&gt;,             
], domContainer);
}) ()

Below is the full warning message:

react-dom.development.js:524 Warning: Each child in a list should have a unique &quot;key&quot; prop. See LINK TO WEBSITE for more information.
warningWithoutStack	@	react-dom.development.js:524
warning	@	react-dom.development.js:1012
warnForMissingKey	@	react-dom.development.js:14793
warnOnInvalidKey	@	react-dom.development.js:15259
reconcileChildrenArray	@	react-dom.development.js:15310
reconcileChildFibers	@	react-dom.development.js:15744
reconcileChildren	@	react-dom.development.js:18242
updateHostRoot	@	react-dom.development.js:18713
beginWork$1	@	react-dom.development.js:20336
beginWork$$1	@	react-dom.development.js:25902
performUnitOfWork	@	react-dom.development.js:24841
workLoopSync	@	react-dom.development.js:24817
performSyncWorkOnRoot	@	react-dom.development.js:24416
scheduleUpdateOnFiber	@	react-dom.development.js:23844
updateContainer	@	react-dom.development.js:27249
(anonymous)	@	react-dom.development.js:27674
unbatchedUpdates	@	react-dom.development.js:24579
legacyRenderSubtreeIntoContainer	@	react-dom.development.js:27673
render	@	react-dom.development.js:27754
(anonymous)	@	apps-dist.js:1
(anonymous)	@	apps-dist.js:1

答案1

得分: 1

你需要在你的 ListItem 组件中添加 key 属性,这样警告就会消失。但是你不能通过 props 传递它,因为它是一个React保留的 prop。

const ListItem = props => {
  return (
    <li key={`${props.title}${props.index}`} className="my-list" onClick={props.onDelete}>
        {props.title}
    </li>
  )
}

<ul className="list-unstyled">
  {this.state.items.map((item, index) => {
    return (
      <ListItem key={index} title={item} onDelete={this.deleteItemHandler.bind(this, item)} index={index} />
    )
  })}
</ul>

你应该尝试连接唯一的信息来创建你的 key 属性。仅使用 map 函数的索引不是一个好的做法。

英文:

You need to add key property to your ListItemcomponent so the warning will disappear. But you can't pass it through props because it's a React reserved prop.

const ListItem = props =&gt; {
return (
&lt;li key={`${props.title}${props.index}`} className=&quot;my-list&quot; onClick={props.onDelete}&gt;
{props.title}
&lt;/li&gt;
)
}
&lt;ul className=&quot;list-unstyled&quot;&gt;
{this.state.items.map((item, index) =&gt; {
return (
&lt;ListItem key={index} title={item} onDelete={this.deleteItemHandler.bind(this, item)} index={index} /&gt;
)
})}
&lt;/ul&gt;

You should try to concatenate unique information to create your key prop. Using only the index of the map function is not a good practice.

答案2

得分: 1

render() {
return (
&lt;div&gt;
&lt;p style={{&#39;fontWeight&#39;: &#39;700&#39;}}&gt;{this.props.intro}&lt;/p&gt;
&lt;ul className=&quot;list-unstyled&quot;&gt;
{this.state.items.map((item, index) =&gt; {
return (
&lt;ListItem key={index} title={item} onDelete={this.deleteItemHandler.bind(this, item)} /&gt;
)
})}
&lt;/ul&gt;
&lt;button onClick={this.addItemHandler.bind(this)} className=&quot;btn btn-sm btn-success&quot;&gt;Add&lt;/button&gt;
&lt;/div&gt;
)
}
英文:

Try this

render() {
return (
&lt;div&gt;
&lt;p style={{&#39;fontWeight&#39;: &#39;700&#39;}}&gt;{this.props.intro}&lt;/p&gt;
&lt;ul className=&quot;list-unstyled&quot;&gt;
{this.state.items.map((item, index) =&gt; {
return (
&lt;ListItem key={index} title={item} onDelete={this.deleteItemHandler.bind(this, item)} /&gt;
)
})}
&lt;/ul&gt;
&lt;button onClick={this.addItemHandler.bind(this)} className=&quot;btn btn-sm btn-success&quot;&gt;Add&lt;/button&gt;
&lt;/div&gt;
)
}

答案3

得分: 0

以下是翻译好的部分:

"Add key prop on BuildList" 变为 "在 BuildList 上添加 key 属性"
"or don't make it an array" 变为 "或者不要将其设置为数组"

英文:

It could be caused by this

//Final output
ReactDOM.render(
[
&lt;BuildList data = {[&#39;Item 1&#39;,&#39;Item 2&#39;, &#39;Item 3&#39;, &#39;Item 4&#39;]} intro=&quot;My first React list&quot; /&gt;,             
], domContainer);
}) ()

Add key prop on BuildList

//Final output
ReactDOM.render(
[
&lt;BuildList key={1} data = {[&#39;Item 1&#39;,&#39;Item 2&#39;, &#39;Item 3&#39;, &#39;Item 4&#39;]} intro=&quot;My first React list&quot; /&gt;,             
], domContainer);
}) ()

or don't make it an array

//Final output
ReactDOM.render(
&lt;BuildList data = {[&#39;Item 1&#39;,&#39;Item 2&#39;, &#39;Item 3&#39;, &#39;Item 4&#39;]} intro=&quot;My first React list&quot; /&gt;,             
, domContainer);
}) ()

答案4

得分: 0

Codesandbox链接

我使用您的代码重现了一个最小示例。在添加了 key={index} 之后,我没有看到任何警告。但是,如果您移除 "key" 属性,您将会看到警告。

英文:

Codesandbox Link

I have reproduced a minimal example using your code. After adding key={index}, i do not see any warnings. However if you remove "key" attribute, you will see warnings.

huangapple
  • 本文由 发表于 2020年1月3日 18:05:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/59576578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定