javascript - 过滤器和钩子导致重新渲染问题
问题描述
我有一个正在用 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 </>)
}
解决方案
推荐阅读
- javascript - 带有 Intent 的 Alexa 调用名称不起作用
- python - tensorflow:在变量中找到较大的值并替换它
- c - 对联合数据的原始访问
- java - 在哪里可以看到 Gradle 在 IntelliJ 上构建的 Hello World 的输出?
- android - 通过 Google Drive API 在 Android 上以编程方式创建多个文件经常会创建重复文件?
- autohotkey - 如何使自动热键在“OneNote for Windows 10”应用程序(不是 OneNote)中工作?
- php - Checkout API 设置指南引用了杀死测试页面且 API 中不存在的命令
- php - 邮件功能的主题问题 - PHP
- elasticsearch - Logstash 未在 ES 上以正确格式存储数据
- laravel-5 - 如何在 netbeans 中为 laravel 5.6 设置自动完成