如何在React中解决'TypeError:无法读取属性'secure_url'的'null'

问题描述 投票:0回答:2

我使用Cloudinary上传图像,然后显示图像和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>
    )
  }
reactjs create-react-app cloudinary
2个回答
0
投票

要处理null或undefined,可以将条件更改为:if ( response.body.secure_url && response.body.secure_url !== '' )

这会检查以确保安全URL在确定它是否不等于空字符串之前存在一些真值(因为技术上null不等于空字符串,因此现有条件不会检查您感兴趣的所有内容) 。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.