【发布时间】:2019-07-11 10:46:42
【问题描述】:
为了我的项目的需要,我必须在两种组织reducer中的实体之间进行选择。
情况是 API 只返回同一对象(本例中为汽车)的不同视图所需的数据。
所以第一种方法是使用标准化状态存储非标准化数据,但使用选择器来避免对象具有视图不需要的数据
const store = {
entities: {
car: {
1: {
id: 1,
name: "SuperCar",
date: "1992",
constuctor: "Super Constructor",
},
2: {
id: 2,
name: "BasicCar",
date: "1987",
picture: "...",
constuctor: "Amazing Constructor",
possessors: [3,45,34]
}
},
possessors: {
/// ...
}
},
requestResult: {
car_for_list: [2],
car_for_home: [1, 2],
}
}
const getCarsForHome = state => state.requestResult.car_for_home.map(id => state.entities.car[id])
陷阱是:
- 我不知道实体数据的一致性
我看到的第二种方法是考虑拥有一个主实体(如父类)并使用选择器来获取视图的正确数据。 主实体拥有所有视图的所有共享属性,而特定实体拥有其他实体。
const store = {
entities: {
car: {
1: {
id: 1,
name: "SuperCar",
date: "1992",
car_for_home: 1, // key to get the details for home view,
},
2: {
id: 2,
name: "BasicCar",
date: "1987",
car_for_home: 2, // key to get the details for home view,
car_for_list: 2 // key to get the details for list view
}
},
car_for_home: {
1: {
id: 1,
constuctor: "Super Constructor",
},
2: {
id: 2,
constuctor: "Amazing Constructor",
}
},
car_for_list: {
2: {
id: 2,
picture: "...",
possessors: [3,45,34]
}
},
possessors: {
/// ...
}
}
}
//Selector
const getCarsForHome = state => Object.values(state.entities.car_for_home).map( car => ({ ...state.entities.car[car.id], ...car }))
陷阱是:
- 如果更新或删除,商店很难维护
- 如果视图需要显示新属性,我可能需要修改我的存储(例如:car_for_list 现在需要构造函数,所以我必须将它存储在主
car)
那么,处理这个问题的最佳方法是什么?
所以你知道,这个项目很大,生产并且会扩大规模。
【问题讨论】:
-
我认为
car_for_detail应该是car_for_list在第二种方式的陷阱中
标签: javascript reactjs redux