首页 > 解决方案 > 如何在 React Native 中将数组分配为对象的属性?

问题描述

这是我的课程模型。时隙是一个时间间隔。不同的课程有不同的插槽。我将在 Appointment 模型中使用这些插槽,因此用户可以选择一个插槽并进行约会。我在存储时隙时遇到问题。

class Course {
  constructor(
    id,
    mentorId,
    categoryId,
    duration,
    title,
    imageUrl,
    description,
    slots
  ) {
    this.id = id;
    this.mentorId = mentorId;
    this.categoryId = categoryId;
    this.duration = duration;
    this.title = title;
    this.imageUrl = imageUrl;
    this.description = description;
    this.slots = slots;
  }

我需要这样的东西:

class Course {
  constructor(
    id,
    mentorId,
    categoryId,
    duration,
    title,
    imageUrl,
    description,
    **slots[]**
  ) {
    this.id = id;
    this.mentorId = mentorId;
    this.categoryId = categoryId;
    this.duration = duration;
    this.title = title;
    this.imageUrl = imageUrl;
    this.description = description;
    this.slots = slots;
  }

如何将此数组分配为对象属性?或者我怎样才能存储这个插槽属性?谢谢你的帮助。

标签: react-nativereact-redux

解决方案


您可以使用类或接口并放置如下内容:

class Slot {
  attribute_1: type_1;
  attribute_2: type_2;
  ....
} 

或者

interface Slot {
  attribute_1: type_1;
  attribute_2: type_2;
  ....
} 

然后在课程类中声明您的插槽数组,如下所示:

class Course {
    id: any;
    mentorId: any;
    categoryId: any;
    duration: any;
    title: any;
    imageUrl: any;
    description: any;
    slots: Slot[]; // or slots: Array<Slot>;
    constructor(
        id: any,
        mentorId: any,
        categoryId: any,
        duration: any,
        title: any,
        imageUrl: any,
        description: any,
        slots: Slot[] // or slots: Array<Slot>;
    ) {
        this.id = id;
        this.mentorId = mentorId;
        this.categoryId = categoryId;
        this.duration = duration;
        this.title = title;
        this.imageUrl = imageUrl;
        this.description = description;
        this.slots = slots;
    }
}

any只是为了示例而输入了类型,因此请随意更改属性的类型。

您还可以通过以下方式处理 null:

slots: Array<Slot> | null;

推荐阅读