[英]Simple solution for “Warning: Each child in an array or iterator should have a unique ”key“ prop.”?
I have a simple <Messages />
React component that shows the error/alert/success messages. 我有一个简单的
<Messages />
React组件,它显示错误/警报/成功消息。
The code is simple as this: 代码很简单,如下所示:
render: function () {
return <div>{this.state.messages.map(function (message) {
return (<div className={message.type}>{message.text}</div>);
})}</div>;
}
The error Warning: Each child in an array or iterator should have a unique "key"
occurs because I don't have a key in the <div />
. 错误
Warning: Each child in an array or iterator should have a unique "key"
由于我在<div />
没有键,因此发生Warning: Each child in an array or iterator should have a unique "key"
。 But my message
doesn't have a field that I could call a "key". 但是我的
message
没有一个可以称为“键”的字段。 I thought to use message.text
as key, but it's a little weird... 我以为可以使用
message.text
作为键,但这有点奇怪...
My idea is simple: create a count
variable and use that as a key. 我的想法很简单:创建一个
count
变量并将其用作键。 As this: 因此:
render: function () {
var count = 0;
return <div>{this.state.messages.map(function (message) {
var keyValue = count++;
return (<div key={keyValue} className={message.type}>{message.type}</div>);
})}</div>;
}
Is there a problem in use this solution for this specific case ? 在特定情况下使用此解决方案是否存在问题?
As pointed out by @azium in the comments, you could use index as the key: 正如@azium在评论中指出的那样,您可以使用index作为键:
return <div>{this.state.messages.map(function (message, index) {
return (<div key={index} className={message.type}>{message.text}</div>);
})}</div>;
For simple use this is fine. 简单使用就可以了。 However, this means that each time the list is rendered, the first item has key=0, the second one has key=1 etc.
但是,这意味着每次呈现列表时,第一项的键为0,第二项的键为1,依此类推。
These keys are unique, but will lead to strange results if the message list changes . 这些键是唯一的,但是如果消息列表更改 , 将导致奇怪的结果 。 React uses the keys to track changes, and wants the same key to always identify the same record.
React使用这些键来跟踪更改,并希望使用相同的键来始终标识相同的记录。 React uses this to do efficient updating when one item in the list changes.
当列表中的一项发生更改时,React使用此功能进行有效的更新。 If you add a message to the the list, or rearrange the order, react will produce really strange results.
如果将消息添加到列表中或重新排列顺序,则react会产生非常奇怪的结果。 So the simple method above does not work when the list changes between renders .
因此, 当列表在渲染之间更改时,上面的简单方法不起作用 。
In those cases, it is probably better (as also suggested by @azium in comments), to use a key that uniquely identifies the item (the index does not do this). 在这种情况下,它可能是更好(如也由评论@azium建议),使用唯一标识项(索引不这样做)的一个关键。
Probably something stored in the message itself, such as a unique ID
: 可能是消息本身中存储的东西,例如唯一
ID
:
return <div>{this.state.messages.map(function (message) {
return (<div key={message.ID} className={message.type}>{message.text}</div>);
})}</div>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.