添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

在React中调用axios后,即使数据存在,也无法显示数据

0 人关注

在用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)

带有previewID的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>

除非我点击浏览器中的任何地方,否则图像不会出现。我怎样才能解决这个问题?

javascript
reactjs
axios
cloudinary
user3831527
user3831527
发布于 2021-01-13
1 个回答
Mohit Kushwaha
Mohit Kushwaha
发布于 2021-08-09
0 人赞同

试着把 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)