React设置默认状态

问题描述 投票:1回答:1

我在设置反应中的默认状态方面寻找一些指导。我有一个简单的项目使用typescript和react,允许将文件放到div上。我正在尝试将这些文件存储在状态中,但我在设置默认状态时遇到问题。

export interface IAppState{
    value:string;
    droppedFiles: FileList
}
constructor(props: {}) {
    super(props);
    this.state{
      value:'',
      droppedFiles?:???
    }
}

public render(): JSX.Element {
return (
  <div className="App">         
    <div className="Padding">
      <FileDrop onDrop={this.handleDrop}>
        Drop some files here!
      </FileDrop>
    </div>    
  </div>
);
}


private handleDrop = (files:FileList, event:ReactDragEvent<HTMLDivElement>) => {
this.setState({
    droppedFiles:files
});
    console.log(this.state.droppedFiles);
}

如果从this.state步骤中删除了droppedFiles,它显然会标记为无法找到该值。由于TypeScript的类型安全,它不会接受{}。初始化/设置复杂类型的默认值的正确方法是什么?

我的主要问题是我遇到了typescript的错误,因为我不知道如何使用正确的数据初始化state.droppedFiles属性。我不想在构造函数中为它分配任何数据,当用户实际删除文件时我会这样做。我只是想找到正确的方法让TS知道状态具有'lostFiles'的属性,类型为'FileList':TS Error

如果没有这部分,它会在运行时抛出错误,我期望:Error


因此,要关闭它,事实证明FileList不是File []。为了解决这个问题,我更新了我的界面:

export interface IAppState{    
    droppedFiles: File[];
}

我在我的构造函数中初始化它,如下所示:

constructor(props: {}) {
    super(props);
    this.state = {
      droppedFiles: []      
    }
}

最后更新我的状态我从FileList中提取了每个项目:

private handleDrop = (files:FileList, event:ReactDragEvent<HTMLDivElement>) => {


    // Create an array from the FileList (as this is an array-like object)    
    const filesArr: File[] = Array.from(files);

        // Update the state with our new array
        this.setState({
          droppedFiles: filesArr
        });
      }

这已经解决了我的问题。谢谢你让我走上了正确的道路。荣誉。

reactjs typescript typescript-typings
1个回答
0
投票

这个问题无法推断到任何情况。在此特定情况下,如果无法提供属性的初始值,则应将属性设置为可选:

export interface IAppState{
    value:string;
    droppedFiles?: FileList
}

这意味着在使用droppedFiles的地方,它可以是FileListundefined,它可能需要if (this.state.droppedFiles) ...检查等。

在这种特定情况下的另一个选择是不使用FileList对象(类似于数组)并存储File对象的数组:

export interface IAppState{
    value:string;
    droppedFiles: File[]
}

...

this.state = { droppedFiles: [], ... }

...

this.setState({ droppedFiles: Array.from(files) });
© www.soinside.com 2019 - 2024. All rights reserved.