从事件中获取文件时,typescript 对象可能为空

Jon*_*Lee 2 javascript components typescript reactjs

我正在尝试制作打字稿 + 反应文件输入组件。但是,我收到打字稿错误“对象可能为空”。我用谷歌搜索但找不到这个问题的解决方案。如何在不禁用打字稿空检查的情况下解决此问题。

我在 e.target.files[0] 上遇到错误!

这是下面的代码

import React from 'react';


    export default function ImageUpload() {
      const [selectedFile, setSelectedFile] = React.useState<File | string>('fileurl');
      const [imagePreviewUrl, setImagePreviewUrl] = React.useState<string | undefined | ArrayBuffer | null>();

      const fileChangedHandler = (e : React.ChangeEvent<HTMLInputElement>) => {
        setSelectedFile(e.target.files[0]!);

        const reader = new FileReader();

        reader.onloadend = () => {
          setImagePreviewUrl(reader.result);
        };

        reader.readAsDataURL(e.target.files[0]!);
      };

      const submit = () => {
        const fd = new FormData();

        fd.append('file', selectedFile);
      };

      let imagePreview = (<div className="previewText image-container">Please select an Image for Preview</div>);
      if (imagePreviewUrl) {
        imagePreview = (
          <div className="image-container">
            <img src={imagePreviewUrl} alt="icon" width="200" />
            {' '}
          </div>
        );
      }

      return (
        <div className="App">
          <input type="file" name="avatar" onChange={fileChangedHandler} />
          <button type="button" onClick={submit}> Upload </button>
          { imagePreview }
        </div>
      );
    }
Run Code Online (Sandbox Code Playgroud)

kin*_*ser 8

HTMLInputElement有一个内置属性filestypeof FileList | null

files: FileList | null; 
Run Code Online (Sandbox Code Playgroud)

只要确保该可能性filesnull

if (!e.target.files) return;
Run Code Online (Sandbox Code Playgroud)

在函数的开头。


Max*_*kov 6

从代码中,我怀疑它e.target可以为空。您可以修改e.target.files[0]!e.target!.files[0]!,这将使错误消失,因为您实际上会告诉 Typescript 编译器“它不会为空,相信我”。但相反,我建议正确处理 null 情况 - 检查 null 或未定义并执行适当的操作,具体取决于您的应用程序逻辑。

  • 建议在“null”概率很高的情况下使用 null 断言是一种不好的做法。 (2认同)
  • 同意,这也是我的回答的主要内容。 (2认同)

Vik*_*ski 6

伙计们,这是处理此问题的正确方法:

            e.target.files instanceof FileList
              ? reader.readAsDataURL(e.target.files[0]) : 'handle exception'
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。干杯!