React-Redux show popup only once everyday

2019-08-02 08:33发布

问题:

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.

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

回答1:

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

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)

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.