反应应用程序本地存储未设置 [英] react app local storage is not setting up

查看:20
本文介绍了反应应用程序本地存储未设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  • 我正在尝试构建一个 React 应用程序,我可以在其中看到类似于 stackoverflow 的通知.
  • 当我打开两个不同的选项卡并打开 stackoverflow 时.我在两个不同的标签中看到通知.
  • 但是当我点击那个通知图标时,数字就会消失.
  • 类似地,在另一个选项卡中,数字也会消失而不刷新页面.
  • 我通过在 ie 和 chrome 中打开来分析 stackoverflow 站点
  • 当我在 chrome 浏览器中点击声望时,我看到一个网络呼叫发生,而在 IE 浏览器中没有刷新数字显示.
  • 我在本地存储和会话存储中看到了一些值.
  • 不调用api可以实现吗,暂时可以用mock数据实现
  • 我构建了标签 ui 并重定向到标签页
  • 所以我用谷歌搜索并找到了这个链接消息通知方案

    https://codesandbox.io/s/material-demo-j5ec5

    demo.js

     anotherPage = () =>{console.log("redictToStepper --->");this.props.history.push("/anotherPage");如果(!事件){console.log("窗口--->");事件 = window.event;}//即 suq如果(!event.newValue)返回;//如果没有可使用的值,则什么都不做if (event.key == "getSessionStorage") {console.log("窗口--->");//另一个选项卡要求 sessionStorage ->发送localStorage.setItem("sessionStorage", JSON.stringify(sessionStorage));//另一个选项卡现在应该有它,所以我们完成了它.localStorage.removeItem("sessionStorage");//<- 也可以做短超时.} else if (event.key == "sessionStorage" && !sessionStorage.length) {//另一个标签发送数据 <- 得到它var data = JSON.parse(event.newValue);for(数据中的var键){sessionStorage.setItem(key, data[key]);}}//监听localStorage的变化如果(window.addEventListener){console.log("窗口--->");window.addEventListener("storage", "xxx", false);} 别的 {console.log("窗口--->");window.attachEvent("onStorage", "xxx");}//请求其他选项卡进行会话存储(这仅用于触发事件)如果(!sessionStorage.length){localStorage.setItem("getSessionStorage", "foobar");localStorage.removeItem("getSessionStorage", "foobar");}};

    pageOne.js

     render() {常量{显示搜索结果,搜索文本,提前输入,typeAheadMode,可编辑,价值} = this.state;const { 类} = this.props;返回 (<div className={classes.root}><AppBar position="static" color="default"><标签价值={价值}onChange={this.handleChange}指标颜色=主要"文本颜色=主要"变体=可滚动"滚动按钮=自动"><Tab label="单选按钮一"/><Tab label="复选框二"/></标签页></AppBar>{值 === 0 &&<TabContainer>通知一</TabContainer>}{值 === 1 &&<TabContainer>通知二</TabContainer>}

);}

解决方案

我无法确定您的 codepen 和 anotherPage 函数试图实现的目标,因此我为您提供 此代码笔.在两个不同的窗口中打开它,查看共享的通知数量.

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

这里如何在两个窗口之间同步你的本地存储,而无需进行任何远程 API 调用:

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

 componentDidMount() {window.addEventListener("storage", this.handleStorageUpdate);}

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

 componentWillUnmount() {window.removeEventListener("storage", this.handleStorageUpdate);}

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

 handleStorageUpdate = storageChange =>{如果(storageChange.key ===通知"){this.setState(() => ({通知:号码(storageChange.newValue)}));}};

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

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

 handleIncreaseNotification = () =>{const 通知 = this.state.notifications + 1;localStorage.setItem("通知", 通知);this.setState(() => ({通知}));};

当增加通知数量时,您将本地存储项设置为由另一个窗口使用.由于您没有监听自己对本地存储的更改,因此您需要将状态设置为这个新的通知数量.

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

 构造函数(道具){超级(道具);const 通知 = localStorage.getItem("notifications") ||0;this.state = { 通知:编号(通知)};}

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

 渲染(){const { 通知 } = this.state;返回 (<div><div>我有 {notifications} 条通知</div><button onClick={this.handleIncreaseNotification}>增加</button>

);}

  • I am trying to build a react app where I can see notifications similar to stackoverflow.
  • when I open two different tabs and open stackoverflow. I see notifications in two different tabs.
  • but when I click that notification icon the numbers diappear.
  • similarly in another tab also number disaapears without refreshing the page.
  • I analysed the stackoverflow site by open in ie and chrome
  • when I click reputation in chrome browser I see a network call happening and in IE browser without refreshing the numbers diappear.
  • I see some values in local storage and session storage.
  • is it possible to achive withot making api calls, for time being can we achieve using mock data
  • I build the tab ui and redirect to the tab page
  • so I google and found this link browser sessionStorage. share between tabs?
  • used it in my react code, for some reason local storage is not setting up
  • its going into this method anotherPage
  • but storage key value is not adding.
  • debugged by putting consoles, but its not printing anything inside window events.
  • can you tell me how to fix it show that I can share the session between different links and tabs.
  • providing my screenhot code snippet and sandbox below

repuation notifications scenario message notifications scenario

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>
    );
  }

解决方案

I had trouble figuring what your codepen and the anotherPage function was trying to achieve, so I am providing you this codepen. Open it in two different windows and look at the shared number of notifications.

Please note that the suggested Local Storage solution is working only on the same browser as browsers does not share their Local Storages.

Here how to synchronize your Local Storage between two windows, without making any remote API call:

First let add an Event Listener. The first argument is the event type (here we are listening to storage), the second one is the callback. Note that listening to storage event works only between two windows (updating storage from a window will not trigger its own listener):

  componentDidMount() {
    window.addEventListener("storage", this.handleStorageUpdate);
  }

Remember to remove this listener when you are not using it anymore (potentially on componentWillUnmount) to prevent any bloat.

  componentWillUnmount() {
    window.removeEventListener("storage", this.handleStorageUpdate);
  }

Now let's take a look at our listener. It will receive all storage changes, but we only want to listen to the notifications changes. When the notifications changes in the storage, we want to update our component state to trigger a rerender with the new value:

  handleStorageUpdate = storageChange => {
    if (storageChange.key === "notifications") {
      this.setState(() => ({ notifications: Number(storageChange.newValue) }));
    }
  };

So now, we are able to have two windows listening to the changes made by each others.

Let's just give a way to increase the amount of notification:

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

    localStorage.setItem("notifications", notifications);

    this.setState(() => ({ notifications }));
  };

When increasing the number of notifications, you are setting the Local Storage item to be consumed by the other window. As you are not listening to your own changes of Local Storage, you need to set your state to this new number of notifications.

As you want to see the notification count directly when opening the window, remember to get the value of your Local Storage at one of the earliest state of your component lifecycle:

  constructor(props) {
    super(props);

    const notifications = localStorage.getItem("notifications") || 0;
    this.state = { notifications: Number(notifications) };
  }

Finally you can render the entire component:

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

这篇关于反应应用程序本地存储未设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆