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

时间:2019-04-29 03:12:06

标签: reactjs create-react-app cloudinary

我正在使用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 个答案:

答案 0 :(得分:0)

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

这将在确定安全URL是否等于空字符串之前进行检查,以确保安全URL是否存在(因为从技术上讲,null不等于空字符串,因此现有条件不会检查您的所有身份)感兴趣)。

答案 1 :(得分:0)

这是React中关于如何将其与上载一起使用的示例代码: https://codesandbox.io/embed/jq4wl1xjv