如何在React Typescript中更新数组

t3psigkw  于 2023-04-22  发布在  TypeScript
关注(0)|答案(1)|浏览(154)

我试图更新我的状态的形式提交,但我得到了一个错误TypeScritp我是新的TS,我不知道如何修复它

enum ServiceTypeEnum {
  Replace = 'replace product',
  Fix = 'fix product',
}

interface IProductName {
  name: string
  serviceType: ServiceTypeEnum
}

const index: FC<Props> = ({ className, ...props }) => {
const [dataArray, setDataArray] = useState({})

const onSubmit: SubmitHandler<IProductName> = data => {
    console.log(data.serviceType)
    setDataArray(prev => [
      ...prev,
      {
        name: data.name,
        type1: data.serviceType[0],
        type2: data.serviceType[1],
        id: Date.now(),
      },
    ])
    console.log(dArray)

    if (data.serviceType.length !== 0 && data.name !== '') {
      console.log(data)
    } else {
      alert('choose name and at least one type')
    }
  }
}

这里是我的错误TS2461: Type '{}' is not an array type
我也在努力

const [dataArray, setDataArray] = useState([])

但我得到了这个错误
TS2345: Argument of type '(prev: never[]) => { name: string; type1: string; type2: string; id: number; }[]' is not assignable to parameter of type 'SetStateAction<never[]>'.Type '(prev: never[]) => { name: string; type1: string; type2: string; id: number; }[]' is not assignable to type '(prevState: never[]) => never[]'. Type '{ name: string; type1: string; type2: string; id: number; }[]' is not assignable to type 'never[]'. Type '{ name: string; type1: string; type2: string; id: number; }' is not assignable to type 'never'.
在JS中没有错误,但我不知道我搜索的typeScript格式,但我什么也没找到

am46iovg

am46iovg1#

这一行:
const [dataArray, setDataArray] = useState({})
可能应该用数组初始化,并键入:
const [dataArray, setDataArray] = useState([] as Array<YourDataType>)
或者:
const [dataArray, setDataArray] = useState<Array<YourDataType>>([])
Typescript在数组没有显式类型化时抱怨的原因是Typescript不知道它是什么类型的数组,所以Typescript假设数组的类型是never[]/Array<never>-一旦你向useState或数组本身添加了一个类型,Typescript就能够理解它。

相关问题