数组或迭代器中的每个子节点都应该有一个唯一的"键"道具。检查"抽象工厂"的渲染方法



尝试在简单的反应组件中呈现一些值,我收到此错误

Each child in an array or iterator should have a unique "key" prop. Check the render method of `Abstractfactory`. See react-warning-keys for more information.
in div (created by Abstractfactory)
in Abstractfactory

class Customer{  
public id: string;
public firstName: string;
public lastName: string;
}
export default Customer;
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";
export default class Abstractfactory extends React.Component<IAbstractFactoryProps, IAbstractFactoryState> {
//Private instance of customerDao, please note it returns ICustomerDao, an Interface,
//not a concrete type
private customerDao: ICustomerDao;
constructor(props: IAbstractFactoryProps, state: IAbstractFactoryState) {
super(props);
this.setInitialState();
// We set the Dao depending on the selected data source
this.setDaos(props.datasource);
//Then we set the list of customers and note, we dont care if they come from Sharepoint
//Rest API or anything else.
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 }>
{this.state.items.map( i => (<div>i.id</div>))}
</div>
</div>
</div>
</div>
);
}
public setInitialState(): void {
this.state = {
items: []
};
}
private setDaos(datasource: string): void {
const data: DataSources = datasource === "Sharepoint" ? DataSources.SharepointList : DataSources.JsonData;
this.customerDao = DaoFactory.getDAOFactory(data).getCustomerDAO();
//Now, its transparent for us a UI developers what datasource was selected
//this.customerDao.
}
}

由于您是在 state.items 上进行映射的,因此您输出的每个<div>标签都需要具有唯一的键属性,以便 React 可以在内部区分它们:

public render(): React.ReactElement<IAbstractFactoryProps> {
return (
<div className={ styles.abstractfactory }>
<div className={ styles.container }>
<div className={ styles.row }>
<div className={ styles.column }>
{this.state.items.map( i => (<div key={i.id}>i.id</div>))}
</div>
</div>
</div>
</div>
);
}

最新更新