我正在构建一个React组件,它接受JSON数据源并创建一个可排序的表。
每个动态数据行都有一个唯一的键分配给它,但我仍然得到一个错误:
数组中的每个子元素都应该有一个唯一的“key”道具。
检查TableComponent的渲染方法。
我的TableComponent渲染方法返回:
<table>
<thead key="thead">
<TableHeader columns={columnNames}/>
</thead>
<tbody key="tbody">
{ rows }
</tbody>
</table>
TableHeader组件是单行,也有一个唯一的键赋给它。
行中的每一行都是由一个具有唯一键的组件构建的:
<TableRowItem key={item.id} data={item} columns={columnNames}/>
TableRowItem看起来是这样的:
var TableRowItem = React.createClass({
render: function() {
var td = function() {
return this.props.columns.map(function(c) {
return <td key={this.props.data[c]}>{this.props.data[c]}</td>;
}, this);
}.bind(this);
return (
<tr>{ td(this.props.item) }</tr>
)
}
});
是什么导致唯一键道具错误?
列表中的每个子元素都应该有一个唯一的“key”道具。
通过在呈现元素中的key属性中声明index值来解决。
App.js组件
import Map1 from './Map1';
const arr = [1,2,3,4,5];
const App = () => {
return (
<>
<Map1 numb={arr} />
</>
)
}
export default App
Map.js组件
const Map1 = (props) => {
let itemTwo = props.numb;
let itemlist = itemTwo.map((item,index) => <li key={index}>{item}</li>)
return (
<>
<ul>
<li style={liStyle}>{itemlist}</li>
</ul>
</>
)
}
export default Map1
我不做详细的解释,但这个答案的关键是“关键”
只需将key属性放在标签中,并确保每次迭代时都赋予它唯一的值
#确保键的值不与其他值冲突
例子
<div>
{conversation.map(item => (
<div key={item.id } id={item.id}>
</div>
))}
</div>
conversation是一个数组,如下所示:
const conversation = [{id:"unique"+0,label:"OPEN"},{id:"unique"+1,label:"RESOLVED"},{id:"unique"+2,label:"ARCHIVED"},
]
警告:数组或迭代器中的每个子元素都应该有一个唯一的“key”道具。
这是一个警告,因为我们要迭代的数组项需要一个唯一的相似性。
React将迭代组件渲染处理为数组。
更好的解决方法是为你要遍历的数组项提供索引。例如:
class UsersState extends Component
{
state = {
users: [
{name:"shashank", age:20},
{name:"vardan", age:30},
{name:"somya", age:40}
]
}
render()
{
return(
<div>
{
this.state.users.map((user, index)=>{
return <UserState key={index} age={user.age}>{user.name}</UserState>
})
}
</div>
)
}
index是React内置的道具。