我有一个正在用 tus 构建的文件系统。所以对于每个文件上传,我都会有一个带有 ReactElement 的数组,它将启动上传过程。将元素添加到数组中没有问题,但我面临的是删除上传的问题,如果说我上传了一个文件并希望将其从数组中删除。使用 filter() 将创建一个新数组,导致我的 ReactElement 重新渲染 = 重新上传文件夹。我尝试过使用也不行的拼接方法。请指教。
const [files, addFile] = useState<JSX.Element>([]);
const startUpload = (e: React.ChangeEvent<HTMLInputElement>): void => {
// some code here
addFile([...files, <File/>]
// <File delete={deleteUpload}/> contains the tus uploading process
}
const deleteUpload = (name: string): void => {
// Using filter() method
addFile(prevState => prevState.filter(file => file.name !== name))
// Using splice
let temp = [...files];
for(let i=0; i<temp.length; i++){
if(temp[i].name === name){
temp.splice(i,1)
}
}
addFile(temp)
// Both filter() and splice() does not work as filter() cause my <File/> to
// re-render within the array and splice() will delete everything below
}
//根据评论进一步编辑<File/>
看起来类似于
const File = (props) => {
useEffect(()=>{
let uploadOptions: any = {
endpoint: 'http://localhost:5000/files',
chunkSize: 8 * 1024 * 1024,
resume: true,
retryDelays: [0, 3000, 5000, 10000, 20000],
headers: {
filename: file.name,
filetype: file.type,
},
metadata: {
filename: file.name,
filetype: file.type,
},
onError(error: any) {
console.log(`Failed because: ${error}`);
},
onProgress(bytesUploaded: number, bytesTotal: number) {
const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2);
console.log(bytesUploaded, bytesTotal, percentage + "%")
},
onSuccess() {
console.log("Download %s from %s", upload.file.name, upload.url)
},
};
// Create a new tus upload
upload = new tus.Upload(file, uploadOptions);
upload.start() // starting the upload process the moment I drop a file in
},[])
return (<> some progress bars and stop buttons to stop pause upload </>)
}