过滤器和挂钩导致重新渲染问题

时间:2020-09-25 01:22:06

标签: javascript reactjs react-hooks tus

我有一个使用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 </>)
}

0 个答案:

没有答案