【发布时间】:2019-10-16 13:07:33
【问题描述】:
- 我正在尝试构建一个反应应用程序,我可以在其中看到类似于 stackoverflow 的通知。
- 当我打开两个不同的选项卡并打开 stackoverflow。我在两个不同的标签中看到通知。
- 但是当我点击那个通知图标时,数字消失了。
- 类似地,在另一个选项卡中,数字也会在不刷新页面的情况下消失。
- 我通过在 ie 和 chrome 中打开分析了 stackoverflow 网站
- 当我在 chrome 浏览器中单击信誉时,我看到发生网络呼叫,并且在 IE 浏览器中没有刷新数字消失。
- 我在本地存储和会话存储中看到了一些值。
- 不调用api可以实现吗,暂时可以用mock数据实现
- 我构建了标签 ui 并重定向到标签页
- 所以我在谷歌上找到了这个链接browser sessionStorage. share between tabs?
- 在我的反应代码中使用它,由于某种原因本地存储没有设置
- 它进入这个方法的另一个页面
- 但未添加存储键值。
- 通过放置控制台进行了调试,但它没有在窗口事件中打印任何内容。
- 你能告诉我如何解决它,表明我可以在不同的链接和标签之间共享会话。
- 在下面提供我的屏幕截图代码 sn-p 和沙箱
https://codesandbox.io/s/material-demo-j5ec5
demo.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>
);
}
【问题讨论】:
-
我做了一些更改以在 codesandbox.io/s/material-demo-6ikw1 中获取本地和会话存储。你应该在点击的参数中传递事件和你想要做的存储类型。
-
你能否给你的代码更改提供 cmets,因为如果我在会话存储和本地存储中看到我没有看到添加的值
-
请立即查看。我可以在日志中看到会话存储。
-
@Ganeshchaitanya 嘿,但是每次我提交时,我都需要更新该选项卡组件中的通知,类似于 stackoverflow 通知,例如它们关闭浏览器并可以再次看到通知。在我的问题中提供了屏幕截图
-
您是否尝试过为此使用 websockets ?
标签: javascript html reactjs redux local-storage