javascript - 如何在 React.js 上解析 "Warning: Encountered two children with the same key"

标签 javascript reactjs

我正在尝试使用来自 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/

相关文章:

javascript - 如何获取元素:hover style?

javascript - JSX for...in 循环

php - Javascript:检查用户是否对代码片段进行了更改

reactjs - 使用 react-apollo,如何使用 TypeScript 在同一组件中定义 2 个突变?

reactjs - 在 redux-form 上使用 React-testing-library 时,表单输入不会改变

javascript - 如何将值传递给 javascript 函数?

javascript - 无法摆脱这种类型的错误

node.js - 在单个 Azure 应用程序中使用 Express 后端来 React 应用程序(通过 create-react-app)?

javascript - 如何在 Home Route 中正确设置 react-router-dom?

javascript - 如何在 Konva 阶段添加视频(.mp4、.mov)?