基本上我想要做的是,当页面刷新时,我希望呈现与刷新页面时呈现的相同的组件。如何获取正在渲染的组件的名称。此外,我在项目中的任何地方都没有使用过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
};
然后在渲染某个组件时为该对象设置值 举个例子: 在组件 1 中 所有组件中的 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
};
关于javascript - 如何在不使用react-router的情况下知道页面刷新之前正在渲染哪个组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57765384/