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

React组件渲染抽象工厂返回的多数据项问题

如何在React组件中渲染抽象工厂模式返回的Customer数据

Hey Luis,看起来你已经把抽象工厂模式的核心逻辑跑通了,数据也能正常拿到,现在就差把这些Customer对象转换成能显示的UI元素啦!

问题分析

你当前直接在JSX中写{this.state.items},React无法直接渲染对象数组,只会把它们转换成[object Object],[object Object]这样的字符串,所以看不到实际的用户数据。我们需要把每个Customer对象映射成React可识别的UI节点。

解决方案步骤

  1. 修正State的初始化与类型定义
    确保IAbstractFactoryState接口正确声明items为Customer[]类型,同时简化构造函数里的state初始化逻辑,避免重复赋值。

  2. 用map遍历数组渲染UI
    在render方法中,通过Array.prototype.map遍历this.state.items,把每个Customer转换成对应的JSX元素(比如列表项),记得给每个元素添加唯一的key属性(这里用customer.id就很合适)。

修改后的完整代码(AbstractFactory.tsx)

import * as React from 'react';
import { IAbstractFactoryProps } from "./IAbstractFactoryProps";
import { IAbstractFactoryState } from "./IAbstractFactoryState";
import styles from './Abstractfactory.module.scss';
import { escape } from '@microsoft/sp-lodash-subset';
import DaoFactory from "./DaoFactory";
import ICustomerDao from "./ICustomerDao";
import DataSources from "./DatasourcesEnum";
import Customer from "./Customer"; // 别忘了显式导入Customer类型

export default class Abstractfactory extends React.Component<IAbstractFactoryProps, IAbstractFactoryState> {
  private customerDao: ICustomerDao;

  constructor(props: IAbstractFactoryProps) {
    super(props);
    this.setDaos(props.datasource);
    // 直接初始化state,去掉冗余的setInitialState方法
    this.state = {
      items: this.customerDao.listCustomers(),
    };
  }

  public render(): React.ReactElement<IAbstractFactoryProps> {
    return (
      <div className={ styles.abstractfactory }>
        <div className={ styles.container }>
          <div className={ styles.row }>
            <div className={ styles.column }>
              <h2>Customer List</h2>
              {/* 遍历items,渲染每个Customer的详细信息 */}
              <ul className={styles.customerList}>
                {this.state.items.map((customer: Customer) => (
                  <li key={customer.id} className={styles.customerItem}>
                    <p><strong>ID:</strong> {escape(customer.id)}</p>
                    <p><strong>Full Name:</strong> {escape(`${customer.firstName} ${customer.lastName}`)}</p>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </div>
      </div>
    )
  }

  private setDaos(datasource: string): void {
    const dataSourceType = datasource === "Sharepoint" ? DataSources.SharepointList : DataSources.JsonData;
    this.customerDao = DaoFactory.getDAOFactory(dataSourceType).getCustomerDAO();
  }
}

额外优化提示

  • 移除了冗余的setInitialState方法,直接在构造函数中初始化state更简洁清晰。
  • 使用escape方法处理用户数据,避免潜在的XSS安全风险(你已经导入了这个方法,正好用上)。
  • 新增了customerList、customerItem样式类,你可以在Abstractfactory.module.scss中添加自定义样式来美化列表:
    .customerList {
      list-style: none;
      padding: 0;
    }
    
    .customerItem {
      border: 1px solid #eee;
      padding: 12px;
      margin-bottom: 8px;
      border-radius: 4px;
    }
    
  • 确保IAbstractFactoryState接口的定义正确(如果还没写的话):
    import Customer from "./Customer";
    
    export interface IAbstractFactoryState {
      items: Customer[];
    }
    

这样修改后,你就能看到两个模拟的Customer数据被渲染成清晰的列表项啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:07:19