我使用的是reactJS和typescript的代码。执行命令时,我得到错误。
我还添加了import语句 import'bootstrap / dist / css / bootstrap.min.css'; 在Index.tsx中。
有没有办法解决这个问题?
npm start
client/src/Results.tsx
(32,21): Missing "key" prop for element.
该文件如下“Results.tsx”
import * as React from 'react';
class Results extends React.Component<{}, any> {
constructor(props: any) {
super(props);
this.state = {
topics: [],
isLoading: false
};
}
componentDidMount() {
this.setState({isLoading: true});
fetch('http://localhost:8080/topics')
.then(response => response.json())
.then(data => this.setState({topics: data, isLoading: false}));
}
render() {
const {topics, isLoading} = this.state;
if (isLoading) {
return <p>Loading...</p>;
}
return (
<div>
<h2>Results List</h2>
{topics.map((topic: any) =>
<div className="panel panel-default">
<div className="panel-heading" key={topic.id}>{topic.name}</div>
<div className="panel-body" key={topic.id}>{topic.description}</div>
</div>
)}
</div>
);
}
}
export default Results;
答案 0 :(得分:22)
您正在渲染元素数组,因此React需要key
道具(1)来识别元素并优化事物。
将key={topic.id}
添加到您的jsx:
return (
<div>
<h2>Results List</h2>
{topics.map((topic: any) =>
<div className="panel panel-default" key={topic.id}>
<div className="panel-heading">{topic.name}</div>
<div className="panel-body">{topic.description}</div>
</div>
)}
</div>
);
答案 1 :(得分:0)
这对我有帮助
不应访问 React 特殊道具 https://deepscan.io/docs/rules/react-bad-special-props