gpt4 book ai didi

javascript - Reactjs展现动态值(value)

转载 作者:行者123 更新时间:2023-12-01 01:13:23 24 4
gpt4 key购买 nike

您好,我正在使用以下代码在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com