這是使用離子和反應。
從 PageB 回來時,我試圖重繪 PageA 上的資料。但是,在從 PageB 重定向后,如果不對 PageA 進行硬重繪 ,這將不起作用。
我正在使用 useEffect 獲取資料
//empty array in use state means it will runs once after the component is loaded
useEffect(() => {
console.log(process.env)
fetch(`${process.env.REACT_APP_API_URL}/invoicems/receipt`)
.then(res => res.json())
.then(result => {
setIsLoaded(true)
setItems(result)
console.log(result)
}, (error) => {
setIsLoaded(true)
setError(error)
})
}, [])
資料提取正常并正確顯示。在同一頁面上有一個添加按鈕。代碼如下
<IonFab vertical="bottom" horizontal="end" slot="fixed">
<IonFabButton routerLink="/add-receipt">
<IonIcon icon={add}></IonIcon>
</IonFabButton>
</IonFab>
正確重定向到添加收據頁面。該頁面具有用于創建資料的資料輸入。添加資料后,我使用此代碼重定向到上述頁面。
const saveHandler=()=>{
const receipt={
"ReceiptDate": receiptDate.current!.value,
"Amount":amount.current!.value,
"MerchantId":selectedMerchant,
"ReceiptData":receiptImage?.base64,
"Description":description.current!.value
}
console.log(receipt)
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(receipt)
};
fetch(`${process.env.REACT_APP_API_URL}/invoicems/receipt`, requestOptions)
.then(async (response) => {
if (!response.ok) {
var error = await response.json();
throw Error(JSON.stringify(error))
}else{
history.length>0? history.goBack() : history.replace('home')
}
})
.catch(error => {
console.log(error);
});
}
問題是第一頁上的資料沒有重繪 就不會重繪 。如何解決這個問題?
uj5u.com熱心網友回復:
問題出在 history.goBack() 中。該方法不會呼叫您的 useEffect,因為它尚未卸載然后安裝,該頁面一直在那里。
我建議使用另一種方法,如 history.go() 或另一種不會破壞您的歷史日志的方法。
另一種可能性是使用 useEffect 但將歷史作為依賴項,而不是 []。這樣,例如,只要歷史記錄與您的路徑匹配,您就可以觸發該提取。您可以使用 useHistory 鉤子獲取歷史記錄。
uj5u.com熱心網友回復:
通過執行以下操作找到了解決此問題的方法。[location.key] 每次在頁面之間切換時都會更改。因此,在這種情況下需要使用它作為依賴項。從https://dev.to/zbmarius/react-route-refresh-without-page-reload-1907了解 uselocation
這是 Adam Rich 在評論部分提到的
import { useLocation } from 'react-router';
const location = useLocation();
const location = useLocation();
useEffect(() => {
console.log(location.key)
getData();
},[location.key])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/386876.html
