[英]How to design state based on useReducer
I have the below requirement:我有以下要求:
We have a fleet of 10 trucks .我们有10 辆卡车组成的车队。 Each truck can carry different loads, for our use case the load is medications .每辆卡车可以承载不同的负载,对于我们的用例,负载是药物。 A Truck has:卡车有:
Each Medication has:每种药物都有:
And from my assessment, it is best to use a useReducer to achieve the aim.而且根据我的评估,最好使用 useReducer 来达到目的。 But my challenge is how to construct my state.但我的挑战是如何构建我的 state。
const [truck, setTrucks] = useState([
{
sn: "001001",
model: "LightWeight",
weightLimit: "50",
batteryCapacity: 80,
state: "IDLE",
},
{
sn: "001002",
model: "Middleweight",
weightLimit: "150",
batteryCapacity: 30,
state: "IDLE",
},
//rest data here
]);
export const droneReducer = (state, action) => {
switch (action.type) {
case "REGISTER_TRUCK":
return [
...state,
{
sn: action.truck.sn,
model: action.truck.model,
weightLimit: action.truck.weightLimit,
batteryCapacity: action.truck.batteryCapacity,
state: action.truck.state,
},
];
case "LOAD_TRUCK":
case "CHECK_LOADED":
case "CHECK_AVAILABLE":
case "CHECK_BATTERY_LEVEL":
}
};
Thanks谢谢
Further to my comments, if you wanted it nested you would add a load
property to the Truck
object:根据我的评论,如果您希望它嵌套,您可以向Truck
object 添加一个load
属性:
export const droneReducer = (state, action) => {
switch (action.type) {
case "REGISTER_TRUCK":
return [
...state,
{
sn: action.truck.sn,
model: action.truck.model,
weightLimit: action.truck.weightLimit,
batteryCapacity: action.truck.batteryCapacity,
state: action.truck.state,
load: action.truck.load
// an array of medicines with qty
},
];
case "LOAD_TRUCK":
case "CHECK_LOADED":
case "CHECK_AVAILABLE":
case "CHECK_BATTERY_LEVEL":
}
};
So it might look like load: [{name: 'COVID vaccine', weight: 2, qty: 9000, code: 'CVD19'}]
所以它可能看起来像load: [{name: 'COVID vaccine', weight: 2, qty: 9000, code: 'CVD19'}]
And then you would access it like you would access any other property of a truck: truck.load
.然后您可以像访问卡车的任何其他属性一样访问它: truck.load
。 You can view it's contents, filter it and reset the state with a new value, add stuff to it, remove stuff from it, change the qty of something inside it.您可以查看它的内容,过滤它并使用新值重置 state,向其中添加内容,从中删除内容,更改其中内容的数量。 Anything.任何事物。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.