简体   繁体   English

如何使用 typescript 从 React 中的状态创建新的 object?

[英]How do I create a new object from states in React with typescript?

I have a state in react containing an array of files.我有一个 state 在反应中包含一组文件。 How can I create a new object of type DocumentRequestModel instead?如何改为创建 DocumentRequestModel 类型的新 object? This is what I got so far.这是我到目前为止得到的。 documents is my state containing my files.文件是我的 state 包含我的文件。

export class DocumentRequestModel implements IDocumentRequestModel {
Data!: string;
FileName!: string;
...

This is what I got so far but I get the error message: Type '(string | undefined)[][] |这是我到目前为止得到的,但我收到错误消息:Type '(string | undefined)[][] | undefined' is not assignable to type 'DocumentRequestModel'. undefined' 不可分配给类型 'DocumentRequestModel'。 Type 'undefined' is not assignable to type 'DocumentRequestModel'.类型“未定义”不可分配给类型“DocumentRequestModel”。

const documentModel: DocumentRequestModel = documents?.map(document => [
  document.preview,
  document.name
]);

This is how documents look.这就是文档的外观。

  0: File
    name: "BOM_BR4666_PROJECTTYPE F_04_06_2020.xlsx"
    lastModified: 1586170093516
    lastModifiedDate: Mon Apr 06 2020 12:48:13 GMT+0200 (Central European Summer Time) {}
    webkitRelativePath: ""
    size: 3948
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    preview: "blob:http://localhost:4000/6d4be14b-0c09-45f9-b2c3-50

You can do it by:你可以这样做:

const [docModel,setDocModel] = React.useState<DocumentRequestModel>()

or you want to defined it in array或者你想在数组中定义它

const docModel = new Array<DocumentRequestModel>()

and in you mapping, the documents might be undefined.在您的映射中,文档可能未定义。 You might wanna check if it is not undefined before you call the map function您可能想在调用 map function 之前检查它是否未定义

const documentModel: Array<DocumentRequestModel> = documents && documents.map(document => [
  document.preview,
  document.name
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM