![](/img/trans.png)
[英]Using react-router's history, is there a way to go back to a specific previously rendered page without using push() or replace()?
[英]How to know which component was being rendered before the page was refreshed without using react-router?
基本上,我想做的是刷新頁面時要呈現的內容與刷新頁面時呈現的組件相同。 如何獲得正在渲染的組件的名稱。 另外我在項目的任何地方都沒有使用react-router。 如果沒有react-router,是否可以執行我所要求的?
我使用過onbeforeunload事件來檢測頁面刷新。 現在,我應該如何在其功能中呈現相同的組件? 這段代碼在我的app.js組件的componentDidMount()中
window.onbeforeunload = function(e) { e.preventDefault()
return console.log('Hello123')
};
這是在控制台中記錄Hello123。唯一的問題是獲取最后渲染的組件的名稱。 有什么方法可以使應用記住上次渲染的組件的名稱,並在刷新后檢查是否有名稱,如果有則渲染該組件。
例如,假設我正在渲染一個名為TravellerList的組件,然后單擊一個按鈕,我正在渲染一個名為AddTraveller的組件。 現在,如何不使用react-router來獲取要渲染的組件的名稱並將其存儲在變量中?
我認為如果要在頁面刷新后獲取值,則必須使用本地存儲或Cookie,因為頁面刷新后,JavaScript中的所有對象都將被刷新。 您可以做的是像在“最高級別”組件中那樣創建一個本地存儲或cookie對象。
var myObj = {
component1Rendered:false,
component2Rendered:false,
component3Rendered:false,
component4Rendered:false
};
然后,當u渲染某些組件時,為該對象設置值。例如:在Component1中,所有組件的componentDidMount中的對象都會在渲染時更新該對象。
componentDidMount() {
var myObj = {
component1Rendered:true,
component2Rendered:false,
component3Rendered:false,
component4Rendered:false
};
localStorage.setItem('storeObj', JSON.stringify(myObj));
// please not that this is a sample set statement in your scenario update only the specific value of that object in local-storage
}
發生頁面刷新后,檢查本地存儲對象以找到先前使用函數渲染過的組件,
window.onbeforeunload = function(e) { e.preventDefault()
return console.log('Hello123')
storeObj = localStorage.getItem('storeObj');
// Filter storeObj and get the rendered components
};
你可以試試這個嗎
componentDidMount() {
window.addEventListener('beforeunload', this.onBeforeUnload);
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.onBeforeUnload);
}
onBeforeUnload = (e) => {
const msg = 'Do you want to leave this site?\n\nChanges you made may not be saved.';
e.returnValue = msg;
return msg;
}
你需要反應路由器。 檢查此React Router-刷新后留在同一頁面
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.