gpt4 book ai didi

reactjs - eslint:迭代器中元素缺少 "key"属性(react/jsx-key)

转载 作者:行者123 更新时间:2023-12-03 13:24:09 32 4
gpt4 key购买 nike

我是 React 新手,我正在尝试输出一个包含用户信息的表。但 Eslint 一直给我以下错误:

[eslint] 迭代器 [react/jsx-key] 中元素缺少“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>

如何防止出现此错误?

最佳答案

您应该将键放在循环内的外部元素上:

const peopleCard = this.state.people.map(person => (
<Col key={person.id} sm="4">
<PeopleCard person={person} />
</Col>
));

如果在某些罕见的情况下你有两个元素,那么你可以将键放在 React.Fragment 上:

const peopleCard = this.state.people.map(person => (
<React.Fragment key={person.id}>
<Col key={person.id} sm="4">
<PeopleCard person={person} />
</Col>
<SomeOtherElement />
</React.Fragment>
));

关于reactjs - eslint:迭代器中元素缺少 "key"属性(react/jsx-key),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54401481/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com