node.js 缺少元素的“关键”道具。(ReactJS 和 TypeScript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48266018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:39:20  来源:igfitidea点击:

Missing "key" prop for element. (ReactJS and TypeScript)

node.jsreactjstypescript

提问by Abhinav1singhal

I am using below code for reactJS and typescript. While executing the commands I get below error.

我正在为 reactJS 和 typescript 使用以下代码。在执行命令时,我收到以下错误。

I also added the import statement import 'bootstrap/dist/css/bootstrap.min.css'; in Index.tsx.

我还添加了导入语句 import 'bootstrap/dist/css/bootstrap.min.css'; 在 Index.tsx 中。

Is there a way to fix this issue?

有没有办法解决这个问题?

npm start

client/src/Results.tsx
(32,21): Missing "key" prop for element.

The file is as below "Results.tsx"

该文件如下“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;

回答by kLabz

You are rendering an array of elements, so React needs a keyprop (1) to identify elements and optimize things.

您正在渲染一个元素数组,因此 React 需要一个keyprop ( 1) 来识别元素并优化事物。

Add key={topic.id}to your jsx:

添加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>
);