reactjs - 显示警报并使用状态将其删除
问题描述
当我显示一些警报并关闭其中一个警报时,我需要在刷新页面时保留以前的警报。所以,我需要以某种方式将这些警报的状态保存在本地存储中。有什么解决办法吗?
PS 我需要这个使用 React States 的实现。
解决方案
我记得最近回答了一个类似的问题,但现在我找不到那个答案(很可能它可能已被删除)。这是一种方法。
我想你可以这样保存状态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
推荐阅读
- makefile - Makefile 没有规则来制作所有人都需要的目标 index.html?
- latex - LaTeX 上的技能点表示
- php - 我们如何使用 ,'suppress_filters' = false 来查询 learnpress 或任何其他翻译方式?(使用 wpml 进行翻译)
- winapi - 如何使用动态布局控件删除对话框窗口的边框?
- postgresql - GORM 错误:关系“用户”的“id”列中的空值违反非空约束
- html - 为什么 :checked 不适用于我的单选按钮?
- php - 允许在 WooCommerce 5+ 中重新发送新订单通知
- java - 如何在启动器活动之前执行异步任务,如启动
- sql - Oracle SQL:当表中的记录存在时显示最大值
- laravel - React-Native 图像未通过 Content URI(react-native-camera)使用 Axios(MultiPart 表单数据)上传