如何基于useReducer设计state

How to design state based on useReducer

我有以下要求:

我们有一支 10 辆卡车 的车队。每辆卡车可以承载不同的负载,对于我们的用例 负载是药物卡车有:

每个药物有:

根据我的评估,最好使用 useReducer 来达到目的。但我的挑战是如何构建我的状态。

  1. 我应该嵌套药物部分,还是应该单独放置?

    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
        ]);

  1. 如果它是嵌套的,我将如何在我的 reducer 中呈现它:

    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":
            }
        };

谢谢

根据我的评论,如果您希望它嵌套,您可以将 load 属性 添加到 Truck 对象:

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":
        }
    };

所以它可能看起来像 load: [{name: 'COVID vaccine', weight: 2, qty: 9000, code: 'CVD19'}]

然后您可以像访问卡车的任何其他 属性 一样访问它:truck.load。您可以查看它的内容,过滤它并用新值重置状态,向其中添加内容,从中删除内容,更改其中内容的数量。随便。