From da4d9b85f167f000a5be861bf4b4d34b94d87f80 Mon Sep 17 00:00:00 2001 From: Cabie Wu Date: Mon, 27 May 2024 22:02:46 +0800 Subject: [PATCH] =?UTF-8?q?[Fix]=20=E4=BD=BF=E7=94=A8useRef=E7=B4=80?= =?UTF-8?q?=E9=8C=84file=20bytes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [Why] 因為沒有用useRef紀錄file bytes,導致有些變數變動後重新re-render 造成file bytes被初始化 [How] 使用useRef紀錄file bytes,才可取得最新狀態數值 --- src/App.js | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/App.js b/src/App.js index a73d518..4532376 100644 --- a/src/App.js +++ b/src/App.js @@ -1,11 +1,9 @@ -import React, { useState } from 'react'; +import React, { useState, useRef } from 'react'; import embedImages from './utils/imgToPdf'; import './App.css'; function App() { - // eslint-disable-next-line no-unused-vars - let fileBytes; - // let classText = 'btn btn-primary disabled'; + const fileBytes = useRef(null); const [fileText, setfileText] = useState('Select your files'); const [isButtonDisabled, setButtonDisabled] = useState(true); @@ -34,17 +32,16 @@ function App() { dataBuffer.push(buffer); } } catch (e) { - console.log(e); return e; } } await getFile(); - fileBytes = embedImages(dataBuffer); + fileBytes.current = await embedImages(dataBuffer); convertBtnStatus(false); }; - const convert = (fileBytes) => { - const blob = new Blob([fileBytes], { type: 'application/pdf' }); + const convert = () => { + const blob = new Blob([fileBytes.current], { type: 'application/pdf' }); const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); const fileName = 'file.pdf'; @@ -54,7 +51,7 @@ function App() { }; const clearAllFiles = () => { - fileBytes = null; + fileBytes.current = null; setfileText('Select your files'); convertBtnStatus(true); };