antd upload组件beforeUpload时拿不到set的值

TomMr
  • 21

需求:在使用antd的upload组件时,我想在beforeUpload方法里,将获取的参数传给后端,后端返回oss参数信息后set到状态里,在data方法里作为参数传至阿里云oss
现象:在获取到oss参数set到状态里,发现set是空值(我判断此处也导致data方法里拿不到值),但在接口返回处可以打印到结果。

const [uploadData, setUploadData] = useState<any>({})

// 获取oss配置
    const getUploadParams = (ext?: string) => {
        return getOssPolicy(ext || "").then((data: any) => {  
             onsole.log(data) // 此处有值
            setUploadData({
                action: data.host,
                data: {
                    key: data.key,
                    policy: data.policy,
                    OSSAccessKeyId: data.accessId,
                    callback: data.callback,
                    Signature: data.signature,
                    Expires: data.expire
                }
            })
        })
    }

// beforeUpload方法
const beforeUpload: UploadProps['beforeUpload'] = async (file, fileList) => {
        let ext = file.name.slice(file.name.lastIndexOf('.'))

        await getUploadParams(ext);
        console.log(uploadData) // 此处为空值
        return new Promise((resolve, reject) => {
            return resolve(true);
        });
    }
// data方法
const getUploadData = (value: any) => {                
        let index = value.name.lastIndexOf(".");
        let ext = value.name.substring(index);
        let data: any = uploadData.data;
        return {
            key: data.key + ext,
            policy: data.policy,
            OSSAccessKeyId: data.OSSAccessKeyId,
            callback: data.callback,
            Signature: data.Signature,
            Expires: data.Expires
        };
    }
 


  let uploadProps = {
        name: 'file',
        beforeUpload: beforeUpload,
        data: getUploadData,
    }
<Upload {...props}>
    <Button icon={<UploadOutlined />}>Upload</Button>
  </Upload>
回复
阅读 386
1 个回答
yeachen
  • 2k

是否是因为 setUploadData 是异步导致的。很久没用了但是我记得 setState 是异步的。所以你打印 uploadData 的时候上面那个函数中的 setUploadData 还没执行完呢

demo
写了个demo实现了你的需求,你看看

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏