簡體   English   中英

缺少元素的“關鍵”道具。 (ReactJS 和 TypeScript)

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

我正在為 reactJS 和 typescript 使用以下代碼。 執行命令時出現以下錯誤。

我還添加了導入語句 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;

您正在渲染一個元素數組,因此 React 需要一個key prop ( 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>
);

這對我有幫助

不應訪問 React 特殊道具https://deepscan.io/docs/rules/react-bad-special-props

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM