Я использую Cloudinary для загрузки изображений, затем отображаю изображение и URL. Мои изображения загружаются, но я получаю, что не могу отобразить ни изображение, ни URL, потому что я получаю ошибку TypeError в своем if (response.body.secure_url! == ''. Я исследовал и прочитал, что это потому, что, возможно, я доступ к свойству объекта с нулевым значением
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>
)
}