我有一个函数可以创建一个数据数组。上面写着:
const createMockData = () => {
/* Please do not refactor this function */
return [
createRowData({species: 'Robot', name: 'T-100', Icon: Android, description: "Likes long walks, walking over the bones of it's enemies"}),
createRowData({species: 'Bug', name:'Barry', Icon: BugReport, description: "Likes long walks, and creating problems in all your code"}),
createRowData({species: 'Rabbit', name:'Roger', Icon: Pets, description: "Likes long walks and getting to know the inner you"}),
createRowData({species: null, name: null, Icon: null, description: null}),
]
};
"createRowData"函数是一个外部js文件,其内容为:
const defaultMock = {
species: 'Human',
name : 'Jon Snow',
icon: AcUnit,
description: 'You know nothing, Jon Snow.'
};
const createRowData = ({name, species, Icon, description}) => {
let rowData = defaultMock;
rowData.id = UUID();
rowData.name = name ? name : rowData.name;
rowData.species = species ? species: rowData.species;
rowData.icon = Icon ? Icon : rowData.icon;
rowData.description = description ? description : rowData.description;
return rowData
}
export { createRowData }
当我调用"createMockData"时,它总是用第三行"Roger Rabbit"填充返回的数组。这样的东西:
0: {species: "Rabbit", name: "Roger", icon: {…}, description: "Likes long walks and getting to know the inner you", id: "6be8c1e0-0070-44cd-a17e-c68097ebfcbd"}
1: {species: "Rabbit", name: "Roger", icon: {…}, description: "Likes long walks and getting to know the inner you", id: "6be8c1e0-0070-44cd-a17e-c68097ebfcbd"}
2: {species: "Rabbit", name: "Roger", icon: {…}, description: "Likes long walks and getting to know the inner you", id: "6be8c1e0-0070-44cd-a17e-c68097ebfcbd"}
3: {species: "Rabbit", name: "Roger", icon: {…}, description: "Likes long walks
为什么会这样?
这是因为行
let rowData = defaultMock;
这条线只是将rowData
设置为指向defaultMock
。稍后的所有分配都将在defaultMock
上进行。这意味着每次调用createRowData
时都要更改默认mock。
您想要实现的是创建defaultMock
的副本,将其分配给rowData
并更改该副本。您可以通过以下方式完成:
let rowData = {...defaultMock};