在用axios做了一个
请求,并在一个承诺中得到了响应,信息是存在的,但在
post
的
preview
循环中没有显示出来。除非我在浏览器中点击该页面;然后图像就会出现。这就好像是在数据可用之前,页面就已经渲染了。我试过
.map()
,但结果是一样的。
useEffect()
const [imageObjects, setImageObjects] = useState([])
const onDrop = useCallback(files => {
const uploadUrl = process.env.REACT_APP_CLOUDINARY_UPLOAD_URL
let _imageObjects = imageObjects.length > 0 ? imageObjects : []
for (let file of files) {
const fileName = file.name
const uploadPreset = process.env.REACT_APP_CLOUDINARY_UPLOAD_PRESET
let data = new FormData()
data.append('upload_preset', uploadPreset)
data.append('file', file)
data.append('multiple', false)
axios({
url: uploadUrl,
method: 'post',
data,
withCredentials: false,
onUploadProgress: (e) => {
setProgress(Math.round((e.loaded * 100.0) / e.total))
}).then(res => {
const delete_token = res.data.delete_token
const secure_url = res.data.secure_url
_imageObjects.push({ delete_token, secure_url })
setProgress(0)
}).catch(err => {
console.log('Error: ', err)
setImageObjects(_imageObjects)
带有preview
ID的div
的代码在这里。
<div id="preview" style={{ border: '1px solid black', minHeight: "75", display: 'flex', alignItems: 'flex-end' }}>
{imageObjects && imageObjects.map(img => {
const delete_token = img.delete_token
return (
<span key={img.delete_token}>
<Link href="#" onClick={() => deletePhoto(delete_token)}>
<img src={img.secure_url} alt={img.secure_url} width="75" height="auto" />
</Link>
</span>
除非我点击浏览器中的任何地方,否则图像不会出现。我怎样才能解决这个问题?
试着把
放在回调里面,
用传播语法把新形成的数组传给
。
setImageObjects
then
setImageObjects
axios({ url: uploadUrl, method: 'post', data, withCredentials: false, onUploadProgress: (e) => { setProgress(Math.round((e.loaded * 100.0) / e.total)) }).then(res => { const delete_token = res.data.delete_token const secure_url = res.data.secure_url setImageObjects([...imageObjects,{ delete_token, secure_url setProgress(0)