我是React的新手,我正在尝试输出一个包含用户信息的表。但是Eslint一直在给我以下错误:
[eslint] Missing "key" prop for element in iterator [react/jsx-key]
我不确定是否正确执行了此操作,但是我为用户列表中的每个人分配了唯一的ID号,但不确定为什么该错误持续存在。
所以在我的PeopleCard.js中,我有以下内容:
import React from "react";
import {
Card,
CardImg,
CardText,
CardBody,
CardTitle,
CardSubtitle,
Button
} from "reactstrap";
import PropTypes from "prop-types";
class PeopleCard extends React.Component {
static propTypes = {
person: PropTypes.object,
id: PropTypes.number,
name: PropTypes.string,
company: PropTypes.string,
description: PropTypes.string
};
render() {
return (
<div>
<Card>
<CardImg
top
width="100%"
src="https://via.placeholder.com/318x180.png"
alt="Card image cap"
/>
<CardBody>
<CardTitle>{this.props.person.name}</CardTitle>
<CardSubtitle>{this.props.person.company}</CardSubtitle>
<CardText>{this.props.person.description}</CardText>
<Button>Button</Button>
</CardBody>
</Card>
</div>
);
}
}
export default PeopleCard;
在我的MainArea.js中,我有以下内容:
import React from "react";
import { Container, Row, Col } from "reactstrap";
import PeopleCard from "./PeopleCard";
class MainArea extends React.Component {
constructor() {
super();
this.state = {
people: [
{
id: 1,
name: "John",
company: "Some Company, Inc",
description: "Met at a party."
},
{
id: 2,
name: "Mary",
company: "Some Company, Inc",
description: "Met at a party."
},
{
id: 3,
name: "Jane",
company: "Some Company, Inc",
description: "Met at a party."
}
]
};
}
render() {
let peopleCard = this.state.people.map(person => {
return (
<Col sm="4">
<PeopleCard key={person.id} person={person} />
</Col>
);
});
return (
<Container fluid>
<Row>{peopleCard}</Row>
</Container>
);
}
}
export default MainArea;
以下行引发了错误,我无法弄清原因:
<Col sm="4">
<PeopleCard key={person.id} person={person} />
</Col>
如何防止出现此错误?
答案 0 :(得分:1)
您应该将键放在外部元素上
const peopleCard = this.state.people.map(person => (
<Col key={person.id} sm="4">
<PeopleCard person={person} />
</Col>
));