我正在尝试使用来自 api 的数据,但是当我尝试呈现数据时,出现此错误:
Warning: Encountered two children with the same key,
[object Object]
. Keys should be unique so that components maintain their identity across updates. Non-unique keys may cause children to be duplicated and/or omitted — the behavior is unsupported and could change in a future version.
这是 CodeSandbox 中的一个原型(prototype)... 大概是解决起来很简单的事情,但是我前几天开始研究react。你能帮帮我吗?
最佳答案
改变
<h2 key={movie.toString()}>{movie.title}</h2>
到
<h2 key={movie.id}>{movie.title}</h2>
解释:
React 期望一个类似列表的组件的每一行都有一个唯一的键。它使用此键来确定自上次渲染以来发生了什么变化。否则,列表的更改方式可能不明确。
movie.toString()
不是唯一的。它正在为每一行评估 [object Object]"
。
查看您正在调用的 API,您实际上可能需要做更多类似这样的事情:
<h2 key={movie.event.id}>{movie.event.title}</h2>
关于javascript - 如何在 React.js 上解析 "Warning: Encountered two children with the same key",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54843682/