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

如何将React类组件转为函数组件?map方法使用存疑

ChatHistory 类组件转函数组件方案

直接把类组件改成函数组件的核心改动就是替换this.props的使用方式,其余逻辑完全可以复用:

import React from "react";

function ChatHistory(props) {
  const messages = props.chatHistory.map((msg, index) => (
    <p key={index}>{msg.data}</p>
  ));

  return (
    <div className="ChatHistory">
      <h2>Chat History</h2>
      {messages}
    </div>
  );
}

export default ChatHistory;

关键说明

  • 函数组件通过入参直接接收props,不需要再写this.props,所以原代码里的this.props.chatHistory直接改为props.chatHistory即可,map的遍历逻辑完全不变。
  • 也可以用解构赋值简化写法,让代码更简洁:
import React from "react";

function ChatHistory({ chatHistory }) {
  const messages = chatHistory.map((msg, index) => (
    <p key={index}>{msg.data}</p>
  ));

  return (
    <div className="ChatHistory">
      <h2>Chat History</h2>
      {messages}
    </div>
  );
}

export default ChatHistory;

这种写法直接把chatHistory从props中解构出来,不用重复写props.,是React函数组件的常用写法。

额外提个小细节:尽量避免用index作为元素的key(除非列表是静态且不会重新排序),如果每条消息有唯一标识(比如msg.id),用这个唯一值作为key会更稳妥。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 10:21:00