- 我正在尝试构建一个 React 应用程序,我可以在其中看到类似于 stackoverflow 的通知。
- 当我打开两个不同的选项卡并打开 stackoverflow 时。我在两个不同的选项卡中看到通知。
- 但是当我单击该通知图标时,数字会出现。
- 同样,在另一个选项卡中,数字也会消失而不刷新页面。
- 我通过在 ie 和 chrome 中打开来分析 stackoverflow 站点
- 当我在 chrome 浏览器中单击声誉时,我看到网络呼叫正在发生,并且在 IE 浏览器中没有刷新数字显示。
- 我在本地存储和会话存储中看到了一些值。
- 是否可以不调用api来实现,暂时我们可以使用模拟数据来实现
- 我构建标签 ui 并重定向到标签页
- 所以我谷歌并找到了这个链接浏览器 sessionStorage。在标签之间共享?
- 在我的react代码中使用它,由于某种原因本地存储没有设置
- 它进入这个方法 anotherPage
- 但存储键值没有添加。
- 通过放置控制台进行调试,但它不会在窗口事件中打印任何内容。
- 你能告诉我如何修复它表明我可以在不同的链接和选项卡之间共享会话。
- 在下面提供我的屏幕截图代码片段和沙箱
https://codesandbox.io/s/material-demo-j5ec5
演示.js
anotherPage = () => {
console.log("redictToStepper --->");
this.props.history.push("/anotherPage");
if (!event) {
console.log("window --->");
event = window.event;
} // ie suq
if (!event.newValue) return; // do nothing if no value to work with
if (event.key == "getSessionStorage") {
console.log("window --->");
// another tab asked for the sessionStorage -> send it
localStorage.setItem("sessionStorage", JSON.stringify(sessionStorage));
// the other tab should now have it, so we're done with it.
localStorage.removeItem("sessionStorage"); // <- could do short timeout as well.
} else if (event.key == "sessionStorage" && !sessionStorage.length) {
// another tab sent data <- get it
var data = JSON.parse(event.newValue);
for (var key in data) {
sessionStorage.setItem(key, data[key]);
}
}
//listen for changes to localStorage
if (window.addEventListener) {
console.log("window --->");
window.addEventListener("storage", "xxx", false);
} else {
console.log("window --->");
window.attachEvent("onstorage", "xxx");
}
// Ask other tabs for session storage (this is ONLY to trigger event)
if (!sessionStorage.length) {
localStorage.setItem("getSessionStorage", "foobar");
localStorage.removeItem("getSessionStorage", "foobar");
}
};
pageOne.js
render() {
const {
showSearchResults,
searchText,
typeAhead,
typeAheadMode,
canEdit,
value
} = this.state;
const { classes } = this.props;
return (
<div className={classes.root}>
<AppBar position="static" color="default">
<Tabs
value={value}
onChange={this.handleChange}
indicatorColor="primary"
textColor="primary"
variant="scrollable"
scrollButtons="auto"
>
<Tab label="Radiobutton One" />
<Tab label="checkbox Two" />
</Tabs>
</AppBar>
{value === 0 && <TabContainer>Notification One</TabContainer>}
{value === 1 && <TabContainer>Notification Two</TabContainer>}
</div>
);
}