项目场景:

在编写项目表单的时候,我们经常会使用到下拉选择器,对于选择器value的值一般为string或number类型,此次是为number类型的问题


问题描述:

在使用ts的对象成员时,必须对其赋初值,否则不能使用如batchMes.varietyId或对对象内不存在的值赋值。
const [batchMes, setbatchMes] = useState({
    batchName: '',
    batchNum: '',
    batchMeasure: 0,
    breedFlag: 1,
    // varietyId:0,
    description: '',
    batchTime: ["2020-10-01", "2020-11-01"],

  })
		<Form.Item
              label={'所属品种'}
              name="varietyId"
              rules={[{ required: true, message: '请选择品种' }]}
            >
              <Select
                placeholder="请选择所属品种"
                // value={batchMes.varietyId ? batchMes.varietyId : ''}
                onSelect={(val) => setbatchMes({ ...batchMes, varietyId: Number(val) })}
                showSearch
                filterOption={(input, option) => {
                  if (option && option.title) {
                    return option.title === input || option.title.indexOf(input) !== -1
                  } else {
                    return true
                  }
                }}
              >
                {
                  varietyData && varietyData.map((item: any) => {
                    return (
                      <Select.Option value={item.varietyId} title={item.name} key={item.varietyId}>{item.name}</Select.Option>
                    )
                  })
                }
              </Select>
            </Form.Item>

在这里插入图片描述
此刻就有一个问题,如果一定要赋初值,当该对象成员为string类型我们只要赋为‘ ’空值即可,那么number类型呢?我们不能给定任意一个数值,因为谁也不知道该数值在后端数据库是否存在,也不能是null之类的值,否则后期赋不了number类型。
在这里插入图片描述


原因分析:

这是由于ts的特点类型校验的限定,因此我们只需对该对象做类型说明,或对该对象内会出现的成员做一个类型说明。

解决方案:

1.对对象进行类型说明,赋为any类型,为number类型的成员可不赋初值。但是该方法就无法对其进行类型校验,也就失去了ts的意义。
const [batchMes, setbatchMes] = useState<any>({
    batchName: '',
    batchNum: '',
    batchMeasure: 0,
    breedFlag: 1,
    description: '',
    batchTime: ["2020-10-01", "2020-11-01"],

  })

2.对对象内成员进行类型说明,同时那些初值为空赋值为number类型的成员设为可选,不赋初值即可。

interface batchMesState {
  batchName: string,
  batchNum: string,
  batchMeasure: number,
  breedFlag: number,
  // enabledFlag: number,
  description?: string,
  batchTime: Object,
  varietyId?: number,
  landId?: number,
  breedBatchId?: number,
  objectVersionNumber?: number
}
const [batchMes, setbatchMes] = useState<batchMesState>({
    batchName: '',
    batchNum: '',
    batchMeasure: 0,
    breedFlag: 1,
    description: '',
    batchTime: ["2020-10-01", "2020-11-01"],

  })
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐