【发布时间】:2020-06-23 03:15:55
【问题描述】:
据我所知,我在正确的组件上正确使用了key,但尽管我努力了,但错误仍然存在。
我有一个Notifications 组件,它通过array.map() 呈现单个Notification 组件的列表。通常,当通知的文本是字符串时,这可以正常工作,但是当它是 JSX(例如带有链接的p)时,我不断收到“子元素必须具有唯一键”警告。在这种情况下,只有一个通知,因此键 是唯一的。
这是在 Redux 中设置通知的代码:
props.setNotification({
type: 'error',
domain: 'page/section',
text: (
<p>
An error occurred.{' '}
<a href="/somewhere/else">Learn more</a>
</p>
)
})
通知组件读取 Redux 并循环访问相应的通知:
export const Notifications = ({ notifications, type, domain }) =>
notifications
.filter(
note =>
(!type && !domain) ||
(domain && note.domain === domain) ||
(type && note.type === type),
)
.map((note, i) => (
<Notification key={`note_${i}`} note={note} />
)
最后,单个通知组件只是基本的 JSX(这些组件是 StyledComponents):
const Notification = ({ className, note }) => (
<Notification type={note.type} className={className}>
<Icon name={typeIconMap[note.type]} size="18" />
<Text>{note.text}</Text>
</Notification>
)
警告说:
index.js:2178 Warning: Each child in a list should have a unique "key" prop. See docs for more information.
in p
in div (created by Text)
in Text (created by Notifications)
in div (created by Notification)
in Notification (created by Notifications)
in Notifications (at Notifications/index.js:15)
in Notifications (created by Connect(Notifications))
到目前为止我已经尝试过:
- 向
setNotification中创建的段落添加一个键,但它没有执行任何操作,尽管警告首先指向该元素。 - 使用不同的元素代替
p,例如React.Fragment,但这并没有改变,即使这些元素本身具有静态键。 - 将
key传递到通知组件,但这会导致另一个错误,因为您无法在子项中传递/访问key。 - 将在
Notifications中分配的键更改为比{i}更稳定的键。我尝试了{btoa(note.text)}和其他一些变体,但没有任何效果。如果text只是一个字符串,它甚至可以在直接使用单个Notification时工作(手动给它一个note对象而不是使用Notifications,即使使用JSX 作为text)我不明白为什么这种特定情况会引发错误。
我在这里有什么明显的遗漏吗?为什么当text 是纯字符串时这有效,而当它是 JSX 时则无效。
【问题讨论】:
-
你使用 const 和 element 同名
Notification?
标签: javascript reactjs