You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS与TypeScript中缺失key属性报错,求解决方案

修复React中"Missing 'key' prop"报错的方法

嘿,我来帮你搞定这个报错!你遇到的Missing "key" prop问题,根源是React对列表渲染的规则要求:当你用map循环渲染列表元素时,必须给每个循环出来的最外层元素加上唯一的key属性,而不是把key加到内部的子元素上。

看你的代码,你把key={topic.id}加在了panel-heading和panel-body这两个内部div上,但React需要的是把key放在map返回的最外层那个<div className="panel panel-default">上。

修复步骤

  • 移除内部panel-heading和panel-body上的key属性
  • 把key={topic.id}添加到map返回的最外层<div className="panel panel-default">元素上

修正后的完整代码

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" key={topic.id}>
            <div className="panel-heading">{topic.name}</div>
            <div className="panel-body">{topic.description}</div>
          </div>
        ))}
      </div>
    );
  }
}
export default Results;

这样修改后,重新运行npm start,这个报错就会消失啦。另外提一句,你的Bootstrap引入是没问题的,和这个报错无关哦。

内容的提问来源于stack exchange,提问作者athenatechie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:12:14