![](/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.