reactjs - 警告:列表中的每个孩子都应该有一个唯一的“关键”道具。反应表
问题描述
我收到此警告,但我不知道如何解决。我认为它必须与 react-tables-2 一起使用,完整的警告说:
index.js:1375 Warning: Each child in a list should have a unique "key" prop. See..
in Cell (created by ReactTable)
in div (created by TdComponent)
in TdComponent (created by ReactTable)
in div (created by TrComponent)
in TrComponent (created by ReactTable)
in div (created by TrGroupComponent)
in TrGroupComponent (created by ReactTable)
in div (created by Tbody)
in Tbody (created by ReactTable)
in div (created by TableComponent)
in TableComponent (created by ReactTable)
in div (created by ReactTable)
in ReactTable (at CustomReactTable.js:106)
in div (at CustomReactTable.js:99)
in CustomReactTable (created by Context.Consumer)
in withRouter(CustomReactTable) (at ProductIndexComponent.js:69)
in div (at ProductIndexComponent.js:68)
in ProductIndexComponent (created by Context.Consumer)
in withRouter(ProductIndexComponent) (created by Context.Consumer)
in Route (at Wrapper.js:38)
in div (created by Sidebar)
in div (created by Sidebar)
in Sidebar (at SideBar.js:62)
in div (at SideBar.js:61)
in SideBar (created by Context.Consumer)
in withRouter(SideBar) (at Wrapper.js:36)
in div (at AuthenticatedComponent.js:33)
in AuthenticatedComponent (created by Context.Consumer)
in withRouter(AuthenticatedComponent) (at Wrapper.js:35)
in div (at Wrapper.js:34)
in Wrapper (created by Context.Consumer)
in Route (at App.js:28)
in Switch (at App.js:26)
in Router (created by BrowserRouter)
in BrowserRouter (at App.js:25)
in div (at App.js:24)
in App (at src/index.js:10)
我的控制台中有两次此警告,我检查并尝试使用这些键但它不起作用,有谁知道我应该怎么做才能摆脱这个警告?
编辑:这是通用表的渲染方法,然后我将这个组件用于我需要的每个表,例如ProductTable,我称之为这个组件。
render() {
return (
<div className='main-content'>
{this.state.showDelete && (
<DeleteComponent onCancelDeleteClick={this.onCancelDeleteClick} item={this.state.item} />
)}
<h3>{this.props.modelName}</h3>
{this.loadAddButton()}
{this.loadFunctionalities()}
<ReactTable
data={this.state.data}
columns={this.props.columns}
manual
onFetchData={this.onFetchData}
pages={this.state.pages}
>
</ReactTable>
<div className="total-records-tag">{this.props.modelName}: {this.state.totalItems}</div>
</div >
)
} }
ProductComponent 渲染方法
render() {
return (
<div className='main-content'>
<CustomReactTable columns={this.state.columns} modelName={"Products"} />
</div >
)
}
解决方案
React 通过仅渲染需要刷新的内容进行优化。循环可以倒出要渲染的非唯一组件。您可以使用 key 道具解决它。
假设您有一个员工对象列表。假设每个员工都有一个 id
employees.map(x=> <MyComponent key={x.id}/>)
始终为键使用唯一值。在这种情况下,就像员工 ID 一样。不要使用数组索引。
推荐阅读
- python - 在 Tkinter 的现有窗口中按下按钮时创建一个新窗口
- html - 溢出 - 隐藏滚动条并禁用滚动但不剪切元素
- python - 为什么我的 Pygame 窗口只显示几秒钟?
- python - 从文本文件配置标签时出错
- html - 在打开带有 javascript 的 .hta 时遇到了一些麻烦
- ios - 是否可以将 Decodable 与 Firestore 时间戳/日期一起使用?
- python - Python 错误——赋值前的局部变量引用
- azure - Azure 函数发布失败 - 找不到依赖项目 CS0246 中引用的任何文件
- python - 如何过滤两个关键字的推特数据?
- python - python循环遍历excel文档,更改设置属性后丢失excel文档数据