反应应用程序本地存储未设置

6 html javascript local-storage reactjs redux

  • 我正在尝试构建一个反应应用程序,在这里我可以看到类似于stackoverflow的通知。
  • 当我打开两个不同的选项卡并打开stackoverflow时。我在两个不同的标签中看到通知。
  • 但是当我单击该通知图标时,数字消失了。
  • 同样,在另一个标签中,编号也会消失而无需刷新页面。
  • 我通过在ie和chrome中打开来分析了stackoverflow站点
  • 当我在chrome浏览器中单击信誉时,我看到正在进行网络通话,而在IE浏览器中却没有刷新数字,而消失
  • 我在本地存储和会话存储中看到了一些值。
  • 是否有可能在进行api调用时实现withot,暂时可以使用模拟数据来实现
  • 我构建选项卡ui并重定向到选项卡页面
  • 所以我谷歌,发现这个链接浏览器sessionStorage。标签之间共享?
  • 在我的反应代码中使用了它,由于某种原因未设置本地存储
  • 它进入此方法anotherPage
  • 但存储密钥值未添加。
  • 通过放置控制台进行调试,但未在窗口事件内打印任何内容。
  • 您能否告诉我如何解决它,表明我可以在不同的链接和标签之间共享会话。
  • 在下面提供我的screenhot代码段和沙箱

信誉通知方案 在此处输入图片说明 消息通知方案 在此处输入图片说明

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");
    }
  };
Run Code Online (Sandbox Code Playgroud)

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>
    );
  }
Run Code Online (Sandbox Code Playgroud)

Nam*_*moz 4

我无法确定您的 codepen 和 anotherPage 函数想要实现的目标,因此我向您提供此 codepen。在两个不同的窗口中打开它并查看共享的通知数量。

请注意,建议的本地存储解决方案仅适用于同一浏览器,因为浏览器不共享其本地存储。

以下是如何在两个窗口之间同步本地存储,而不进行任何远程 API 调用:

首先添加一个事件监听器。第一个参数是事件类型(这里我们正在监听存储),第二个参数是回调。请注意,监听存储事件仅在两个窗口之间起作用(从窗口更新存储不会触发其自己的监听器):

  componentDidMount() {
    window.addEventListener("storage", this.handleStorageUpdate);
  }
Run Code Online (Sandbox Code Playgroud)

请记住,当您不再使用此侦听器时(可能在 componentWillUnmount 上)将其删除,以防止任何膨胀。

  componentWillUnmount() {
    window.removeEventListener("storage", this.handleStorageUpdate);
  }
Run Code Online (Sandbox Code Playgroud)

现在让我们看看我们的监听器。它将接收所有存储更改,但我们只想监听通知更改。当存储中的通知发生变化时,我们希望更新组件状态以使用新值触发重新渲染:

  handleStorageUpdate = storageChange => {
    if (storageChange.key === "notifications") {
      this.setState(() => ({ notifications: Number(storageChange.newValue) }));
    }
  };
Run Code Online (Sandbox Code Playgroud)

现在,我们可以让两个窗口监听彼此所做的更改。

我们就给出一个增加通知量的方法:

 handleIncreaseNotification = () => {
    const notifications = this.state.notifications + 1;

    localStorage.setItem("notifications", notifications);

    this.setState(() => ({ notifications }));
  };
Run Code Online (Sandbox Code Playgroud)

增加通知数量时,您将设置本地存储项目以供其他窗口使用。由于您没有监听自己的本地存储更改,因此您需要将状态设置为新的通知数量。

由于您希望在打开窗口时直接查看通知计数,因此请记住在组件生命周期的最早状态之一获取本地存储的值:

  constructor(props) {
    super(props);

    const notifications = localStorage.getItem("notifications") || 0;
    this.state = { notifications: Number(notifications) };
  }
Run Code Online (Sandbox Code Playgroud)

最后你可以渲染整个组件:

  render() {
    const { notifications } = this.state;
    return (
      <div>
        <div> I have {notifications} notifications</div>
        <button onClick={this.handleIncreaseNotification}>increase</button>
      </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)

  • @zizi 本地存储不在浏览器之间共享,您不能使用模拟数据来使其按预期工作,如果您需要通知状态在浏览器之间持久存在,则需要 API。 (2认同)