作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我正在使用以下代码在 Cloudinary 上传图像
import React, { Component } from 'react';
import './App.css';
import Dropzone from 'react-dropzone';
import axios from 'axios';
const FETCH_URL = `https://res.cloudinary.com/${USER_NAME}/image/fetch`;
const options = 'w_300';
export const getUrl = (url, options = '') => {
return `${FETCH_URL}/${options}${encodeURIComponent(url)}`;
};
class App extends Component {
state = {
image: null,
upload: null,
number: '',
};
handleDrop = (files) => {
// Push all the axios request promise into a single array
this.setState({ number: files.length });
const uploaders = files.map(file => {
// Initial FormData
const formData = new FormData();
formData.append('file', file);
formData.append('tags', 'codeinfuse, medium, gist');
formData.append('upload_preset', 'fake'); // Replace the preset name with your own
formData.append('api_key', '444445'); // Replace API key with your own Cloudinary key
formData.append('timestamp', (Date.now() / 1000) | 0);
// Make an AJAX upload request using Axios (replace Cloudinary URL below with your own)
return axios.post('https://api.cloudinary.com/v1_1/what/upload', formData, {
headers: { 'X-Requested-With': 'XMLHttpRequest' },
}).then(({ data }) => {
const fileURL = data.secure_url; // You should store this URL for future references in your app
this.setState({ upload: fileURL });
});
});
// Once all the files are uploaded
axios.all(uploaders)
.then(() => {
return getUrl(this.state.upload, options);
})
.then(photo => this.setState({ image: photo }));
}
render() {
console.log(this.state.upload)
return (
<div className="App">
<Dropzone
onDrop={this.handleDrop}
multiple
accept="image/*"
>
<p>Drop your files or click here to upload</p>
</Dropzone>
<br />
{this.state.upload}
</div>
);
}
}
export default App;
我已在 dropzone 启用多个文件上传。在 cloudinary 上传文件也同样有效。但问题是,当我上传多个文件时,它会生成多个响应,并且值会发生变化。如您所见,我将对状态的响应保存为 this.state.upload
。如何存储所有回复而不丢失任何值(value)。谢谢
最佳答案
您可以这样设置状态:
state = {
imageList: [],
...
}
....
handleDrop = () => {
...
axios.all(...).then(photo => this.setState({ imageList: [...this.state.imageList, photo] }))
}
关于javascript - Reactjs展现动态值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54978198/
我是一名优秀的程序员,十分优秀!