如何使用 createSlice 的 RTK 功能创建具有多个属性的状态?

huangapple go评论92阅读模式
英文:

how to use createSlice's RTK function to create a state that has multiple properties?

问题

我正在在一个React项目中使用Redux-Toolkit来管理我的应用程序的状态。我为顾客创建了一个slice。顾客是一个拥有姓名、ID、食物列表、陪同顾客数量、餐馆位置以及订单日期和时间的对象。

createSlice中,要精确添加所有这些属性到状态,你应该编写以下代码:

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);
        }
      });
    },
    // 添加新属性到状态
    addNewPropertiesToCustomer: (state, action: PayloadAction<NewCustomerProperties>) => {
      state.value.forEach((customer) => {
        if (customer.id === action.payload.id) {
          customer.guestsNumber = action.payload.guestsNumber;
          customer.restauLocation = action.payload.restauLocation;
          customer.orderDate = action.payload.orderDate;
          customer.orderTime = action.payload.orderTime;
        }
      });
    },
  },
});

你需要添加一个新的reducer,名为addNewPropertiesToCustomer,并且使用NewCustomerProperties来作为PayloadAction的类型。这个reducer会将新属性添加到顾客对象中,通过匹配ID来找到正确的顾客对象。

请确保在其他部分定义NewCustomerProperties类型,以便在使用它时类型匹配。

英文:

I am using Redux-Toolkit in a React project to manage the state of my app. I created a slice for customers. A customer is an object that possesses a name, id, list of food, number of guests accompanying them, the location of the restaurant, and the order's date and time.

In createSlice, what code should I write exactly to add all these properties to the state?

I took this project from someone else and initially, the customers' state had only an id, name, and array of food.
Now I want to add the other properties as well.
Here is the Customer Interface:

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

And here is the code of the customerSlice:

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

How do I add these properties to the state?

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

答案1

得分: 0

你可以将新的字段/属性添加到 `Customer` 接口中。

```typescript
export interface Customer {
  id: string;
  name: string;
  food: string[];
  guestsNumber: number | string; // &lt;-- 新属性
  restauLocation: string;        // &lt;-- 新属性
  orderDate: string;             // &lt;-- 新属性
  orderTime: string;             // &lt;-- 新属性
}

我还建议给状态添加更好的属性名称,例如 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;
        ...
      };
    },
  },
});
英文:

You can add the new fields/properties to the Customer interface.

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

I also suggest giving the state better property names, e.g. state.customers is much more informative than state.value. The initialState doesn't really need to have anything new since it's just an array of Customer objects. New actions can be created and can access/modify any Customer properties, e.g. the example someNewAction action below.

Example:

export interface CustomerState {
  customers: Customer[];
}

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

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

      const customer = state.customers.find(customer =&gt; customer.id === id);

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

      const customer = state.customers.find(customer =&gt; customer.id === id);

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

huangapple
  • 本文由 发表于 2023年7月18日 00:27:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76706431.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定