Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

javascript - ReactJS, axios: data not displaying after axios call even though data exists

After making an axios 'post' call to a server and getting the response back in a promise, the information exists but does not show up in the 'preview' .map() loop UNLESS I click in the browser then the images appear. It's as if the page renders before the data is available(I think). I've tried useEffect() etc the result is the same.

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)

    })

The "preview" display code is here:

<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>
            )
      })}
 </div>

Unless I click anywhere in the browser, the images do not appear. How do I solve this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...