首页 > 解决方案 > 显示警报并使用状态将其删除

问题描述

当我显示一些警报并关闭其中一个警报时,我需要在刷新页面时保留以前的警报。所以,我需要以某种方式将这些警报的状态保存在本地存储中。有什么解决办法吗?

PS 我需要这个使用 React States 的实现。

标签: reactjs

解决方案


我记得最近回答了一个类似的问题,但现在我找不到那个答案(很可能它可能已被删除)。这是一种方法。

我想你可以这样保存状态localStorage

  • window.localStorage.setItem()
  • window.localStorage.getItem()

现在我到目前为止所做的是,当我对状态进行任何更改时,我会:

if (window.localStorage) {
  window.localStorage.setItem('alerts', JSON.stringify(alerts));
}

然后当我启动我的应用程序时,即 on componentDidMount,我会:

if (window.localStorage && window.localStorage.getItem('alerts')) {
  this.setState(JSON.parse(window.localStorage.getItem('alerts')));
}

所以这里是完整的代码:

componentDidMount() {
  if (window.localStorage && window.localStorage.getItem('alerts')) {
    this.setState(JSON.parse(window.localStorage.getItem('alerts')));
  }
  // subscribe to new alert notifications
  this.subscription = alertService.onAlert(this.props.id).subscribe(alert => {
    // clear alerts when an empty alert is received
    if (!alert.message) {
      // filter out alerts without 'keepAfterRouteChange' flag
      const alerts = this.state.alerts.filter(x => x.keepAfterRouteChange);
      // remove 'keepAfterRouteChange' flag on the rest
      alerts.forEach(x => delete x.keepAfterRouteChange);
      this.setState({ alerts });
      if (window.localStorage) {
        window.localStorage.setItem('alerts', JSON.stringify(alerts));
      }
      return;
    }
    // add alert to array
    this.setState({ alerts: [...this.state.alerts, alert] });
    // auto close alert if required
    if (alert.autoClose) {
      setTimeout(() => this.removeAlert(alert), 3000);
    }
  });
  // clear alerts on location change
  this.historyUnlisten = history.listen(() => {
    alertService.clear(this.props.id);
  });
}

演示 分叉 StackBlitz:https ://stackblitz.com/edit/react-alerts-rv1qc8


推荐阅读