每天只有一次React-Redux显示弹出窗口 [英] React-Redux show popup only once everyday

查看:273
本文介绍了每天只有一次React-Redux显示弹出窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个React应用程序,并且状态通过Redux存储得以维护.我只想在用户首次加载网站时每天只向用户显示一次弹出消息.

I have a React application and the state is maintained through Redux store. I want to show a popup message to the user only once everyday when he loads the site for the first time.

理想的实现方法是使用本地存储来记住上一次弹出窗口的时间,并且仅当上一次弹出窗口的显示日期不是今天时才显示弹出窗口.

The ideal implementation for this would be to use local storage to remember when the last popup was and show popup only when the last popup show date is not today.

我想知道是否有任何react-redux方式可以做到这一点,以及是否已经有可用的库.

I would like to know if there is any react-redux way of doing this and if there are libraries already available for this.

推荐答案

There are quite a few libraries that can be used to persist your store state (or part of it) to local storage.

可能最受欢迎的是 redux-persist .使用它,您可以执行以下操作:

Probably the most popular of the bunch is redux-persist. Using it you could do something like:

import { combineReducers } from 'redux' 
import { persistStore, persistReducer } from 'redux-persist'
import storage from 'redux-persist/es/storage'

const modalReducer = (state = {}, action) => {
  switch (action.type) {
    case 'SHOW_MODAL':
      return {
        ...state,
        display: true,
        lastShown: new Date()
      }
    case 'HIDE_MODAL':
      return {
        ...state,
        display: false
      }
    default: 
      return state
  }
}

const modalPersistConfig = { key: 'modal', blacklist: ['display'], storage }

const rootReducer = combineReducers({
  modal: persistReducer(modalPersistConfig, modalReducer)
  // other reducers
})

const store = createStore(reducer)
persistStore(store)

然后,您可以在商店(store.getState().modal.lastShown)中检查日期,如果不是今天的日期,则调度SHOW_MODAL操作.

Then you can check the date in the store (store.getState().modal.lastShown) and dispatch a SHOW_MODAL action if it's not today's date.

这篇关于每天只有一次React-Redux显示弹出窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆