redux 如何使用createSlice的RTK函数创建具有多个属性的状态?

7jmck4yq  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(108)

我在一个React项目中使用Redux-Toolkit来管理我的应用程序的状态。我为客户创造了一个切片。客户是一个对象,它拥有一个名字、id、食物列表、陪同他们的客人数量、餐馆的位置以及订单的日期和时间。
createSlice中,我应该编写什么代码来将所有这些属性添加到状态中?
我从别人那里得到了这个项目,最初,客户的状态只有一个ID、名称和食物数组。现在我想添加其他属性。下面是客户界面:

export interface Customer {
  id: string;
  name: string;
  food: string[];
}

字符串
下面是customerSlice的代码:

export const customerSlice = createSlice({
  name: "customer",
  initialState,
  reducers: {
    addCustomer: (state, action: PayloadAction<Customer>) => {
      state.value.push(action.payload);
    },
    addFoodToCustomer: (
      state,
      action: PayloadAction<AddFoodToCustomerPayload>
    ) => {
      state.value.forEach((customer) => {
        if (customer.id === action.payload.id) {
          customer.food.push(action.payload.food);
        }
      });
    },
  },
});


如何将这些属性添加到状态?

guestsNumber: number | string;
restauLocation: string;
orderDate: string;
orderTime: string;

ki1q1bka

ki1q1bka1#

您可以将新字段/属性添加到Customer接口。

export interface Customer {
  id: string;
  name: string;
  food: string[];
  guestsNumber: number | string; // <-- new property
  restauLocation: string;        // <-- new property
  orderDate: string;             // <-- new property
  orderTime: string;             // <-- new property
}

字符串
我还建议给国家更好的财产名称,例如。state.customersstate.value提供的信息要多得多。initialState并不需要任何新的东西,因为它只是一个Customer对象数组。可以创建新操作,并且可以访问/修改任何Customer属性,例如下面的示例someNewAction操作。
示例如下:

export interface CustomerState {
  customers: Customer[];
}

const initialState: CustomerState = {
  customers: [],
};

export const customerSlice = createSlice({
  name: "customer",
  initialState,
  reducers: {
    addCustomer: (state, action: PayloadAction<Customer>) => {
      state.customers.push(action.payload);
    },
    addFoodToCustomer: (
      state,
      action: PayloadAction<AddFoodToCustomerPayload>
    ) => {
      const { id, food } = action.payload;

      const customer = state.customers.find(customer => customer.id === id);

      if (customer) {
        customer.food.push(food);
      };
    },
    ...
    someNewAction: (state, action<.....>) => {
      const { id, guestNumber, location, ...etc... } = action.payload;

      const customer = state.customers.find(customer => customer.id === id);

      if (customer) {
        customer.guestsNumber = guestNumber;
        customer.restauLocation = location;
        ...
      };
    },
  },
});

相关问题