由于功能需求,需要通过接口获取已上传的文件,而且不是通过form包起来,所以initialValue是不可用的,所以我们需要通过fileList来进行数据回显
这里有个坑!我们不能用defaultFileList来进行数据回显,因为我们通过hooks来获取接口数据会显的时候是不能进行对defaultFileList进行覆盖的!!!所以如果你的hooks初始值设置的回显值为空数组useState([]),那么defaultFileList就一直是空数组,在你hooks改变之后也不会改变渲染!!!!
所以我们这边使用fileList来进行数据的回显并且和onChange相配合来进行删除添加等功能来进行hooks的配置
//回显列表展示
const [fileListShow, setFileListShow] = useState([])
//接口上传列表hooks
const [fileUrlList, setFileUrlList] = useState([])
const fileChange = (e) => {
let newFileList = [...e.fileList]
// 1. Limit the number of uploaded files
// Only to show two recent uploaded files, and old ones will be replaced by the new
// newFileList = newFileList.slice(-8)
// 2. Read from response and show file link
//对回显的数据进行处理
newFileList = newFileList.map((file) => {
if (file.response) {
// Component will show file.url as link
file.url = file.response.url
}
return file
})
//对上传的hooks数据进行处理
let fileList = newFileList.map((file) => {
if (file.response) {
return file.response.msg.url
} else if (file.thumbUrl) {
return file.thumbUrl
}
})
setFileUrlList(fileList)
setFileListShow(newFileList)
}
//展示文件
const hanlePreview = async (item) => {
var docarr = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']
var imgarr = ['gif', 'jpg', 'png', 'jpeg', 'JPG', 'PNG']
var index = item.name.lastIndexOf('.')
var type = item.name.substr(index + 1)
var docindex = docarr.findIndex((item) => item === type)
var imgarr = imgarr.findIndex((item) => item === type)
// console.log(item, type, imgarr, docindex);
if (docindex > 0 || docindex == 0) {
// window.open(MiCROSOFT_URL + item.url, '_blank');
window.open(
`https://office.siruijie.com.cn/op/view.aspx?ui=zh-CN&rs=zh-CN&src=${escape(
item.url
)}`,
'_blank'
)
} else if (imgarr > 0 || imgarr == 0) {
// previewClick(item);
await setUrl(item.url)
rcviewer.current.viewer.show()
} else if (type == 'pdf') {
window.open(item.url, '_blank')
} else {
message.error(`当前文件暂不支持在线预览`)
}
}
<ProFormUploadButton
title="点击上传"
max={8}
fieldProps={{
name: 'file',
multiple: true,
onPreview: (file) => hanlePreview(file),
fileList: fileListShow,
withCredentials: true,
}}
action={`${API_URL}api/article/file/upload`}
onChange={fileChange}
/>