开发者问题收集

如何解决 React 中的“TypeError: 无法读取 null 的属性‘secure_url’”

2019-04-29
897

我正在使用 Cloudinary 上传图片,然后显示图片和 URL。图片正在上传,但我无法显示图片或 URL,因为我的 if (response.body.secure_url !== '' 中出现了 TypeError。我研究并读到,这可能是因为我正在访问一个为 null 的对象的属性

App.js

this.state = {
      uploadedFile: null,
      uploadedFileCloudinaryUrl: ''
    };
  }

  onImageDrop(files) {
    this.setState({
      uploadedFile: files[0]
    });

    this.handleImageUpload(files[0]);
  }

  handleImageUpload(file) {
    let upload = request.post(CLOUDINARY_UPLOAD_URL)
                     .field('upload_preset', CLOUDINARY_UPLOAD_PRESET)
                     .field('file', file);


    upload.end((err, response) => {
      if (err) {
        console.error(err);
      }

      if (response.body.secure_url !== '') {
        this.setState({
          uploadedFileCloudinaryUrl: response.body.secure_url
        });
      }
    });
  }

  render() {
    return (
      <div>
      <div className="FileUpload">
      <Dropzone
        onDrop={this.onImageDrop.bind(this)}
        accept="image/*"
        multiple={false}>
        {({getRootProps, getInputProps}) => {
      return (
        <div
          {...getRootProps()}
        >
          <input {...getInputProps()} />
          {
          <p>Try dropping some files here, or click to select files to upload.</p>
          }
        </div>
      )
  }}
</Dropzone>
      </div>

      <div>

        {this.state.uploadedFileCloudinaryUrl === '' ? null :
        <div>
          <p>{this.state.uploadedFile.name}</p>
          <img src={this.state.uploadedFileCloudinaryUrl} />
        </div>}

      </div>
    </div>
    )
  }
2个回答

要处理 null 或未定义的情况,您可以将条件更改为: if ( response.body.secure_url && response.body.secure_url !== '' )

这将检查以确保安全 URL 存在且具有某个真值,然后再确定它是否不等于空字符串(因为从技术上讲 null 不等于空字符串,因此现有条件不会检查您感兴趣的所有内容)。

Philip Wrage
2019-04-29

以下是 React 中有关如何将其与上传结合使用的示例代码: https://codesandbox.io/embed/jq4wl1xjv

Shirly Manor
2019-04-30