React Native 动态检查值是否为必填,然后检查必填值是否为空

0x6upsns  于 2023-01-02  发布在  React
关注(0)|答案(1)|浏览(147)

我有一个对象状态,我将其初始化为initialSegement
当我设置每个字段startDate、endDate等的状态时,我已经创建了这个组件,并且在那里一切都工作正常。
我想创建一个名为validateSegement的函数,它是布尔型的。如果这个函数返回真,那么添加段的按钮将被启用。
我已经创建了这个函数,但遗憾的是它不是动态的。
问题是这些字段是由用户动态配置的,无论它们是否是必填的,所以我想找到一种方法来做到这一点,首先检查字段是否是必填的,然后检查必填字段是否为空。
我可以从后端的响应中找出这些字段是否是强制性的,对于这种情况,我假设响应如下:

cdmah0mi

cdmah0mi1#

type Segment = {
  id: string;
  startDate?: string;
  endDate?: string;
  startTime?: string;
  endTime?: string;
}

type MaybeOptionalField = keyof Omit<Segment, "id">

const configurations: Record<MaybeOptionalField, {mandatory: boolean, text: string}> = {
  startDate: {
    mandatory: true,
    text: "test"
  },
  endDate: {
    mandatory: false,
    text: "test"
  },
  startTime: {
    mandatory: false,
    text: "test"
  },
  endTime: {
    mandatory: false,
    text: "test"
  }
};

const segments: Segment[] = [{
    id: 'foo',
    startDate: "now",
}, {
    id: 'bar',
}]

// figure out which fields are currently required
const mandatoryFields = Object.entries(configurations)
    .filter(([_, configuration]) => configuration.mandatory)
    // Object.entries treats 'key' to always be type any string, but we'd like to maintain the keys as being of type MaybeOptionalField
    // which keeps `segment[mandatoryField]` as being valid, one could instead push the type assertion into the for loop below
    .map(([key]) => key as MaybeOptionalField)

const validateSegment = (segment: Segment) => {
  for (const mandatoryField of mandatoryFields) {
    if (!segment[mandatoryField]) {
      return false
    }
  }
  return true
};

const validSegments = segments.filter(segment => validateSegment(segment))
const invalidSegments = segments.filter(segment => !validateSegment(segment))

console.log(validSegments, validSegments.length)
console.log(invalidSegments, invalidSegments.length)

相关问题