【问题标题】:typescript Object is possibly null when getting files from event从事件获取文件时,打字稿对象可能为空
【发布时间】:2020-08-17 19:05:55
【问题描述】:

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

我在 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>
      );
    }

【问题讨论】:

    标签: javascript reactjs typescript components


    【解决方案1】:

    HTMLInputElement 有一个内置属性 files,即 typeof FileList | null

    files: FileList | null; 
    

    只需确保filesnull 的可能性。

    if (!e.target.files) return;
    

    在函数的开头。

    【讨论】:

      【解决方案2】:

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

                  e.target.files instanceof FileList
                    ? reader.readAsDataURL(e.target.files[0]) : 'handle exception'
      

      希望这会有所帮助。干杯!

      【讨论】:

        【解决方案3】:

        从代码中,我怀疑e.target 可以为空。您可以将 e.target.files[0]! 修改为 e.target!.files[0]!,这将使错误消失,因为您实际上会告诉 Typescript 编译器“它不会为空,相信我”。但相反,我建议正确处理 null 情况 - 检查 null 或 undefined 并根据您的应用逻辑做一些适当的事情。

        【讨论】:

        • null 的概率很高的地方建议一个空断言是不好的。
        • 同意,这也是我的回答本质上的意思。
        猜你喜欢
        • 1970-01-01
        • 2020-11-07
        • 2017-10-12
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 2021-12-01
        • 2019-09-04
        • 2021-09-27
        相关资源
        最近更新 更多