zoukankan      html  css  js  c++  java
  • Redux-persist使用

      redux-persist作用是将store中的数据缓存到浏览器中,减少数据请求,每当白名单中的数据发生变化,才会进行一次更新缓存的操作,并且这个数据缓存是存在localStorage中的,不是会话级别的缓存。

      安装方式两种:npm install --save redux-persist / yarn add redux-persist

      实现方式主要是依靠两个方法:persistStore和persistReducer,使用persistReducer时需要指定persistConfig,这一项就是你需要缓存的数据处理项,它有着黑白名单的处理方式,还需要一个storage的协助:

     1 import {persistStore, persistReducer} from 'redux-persist';
     2 
     3 import storage from 'redux-persist/lib/storage';
     4 
     5 // BLACKLIST
     6 const persistConfig = {
     7   key: 'root', // key是放入localStorage中的key
     8   storage: storage, // storage简单就可以理解成localStorage的功能封装吧,不过有时候由于版本问题,必要在后一个storage上加一个default属性,可以在console中打出来判断是否需要加
     9   blacklist: ['navigation'] // navigation不会被存入缓存中,其他会,适用于少部分数据需要实时更新
    10 };
    11  
    12 // WHITELIST
    13 const persistConfig = {
    14   key: 'root',
    15   storage: storage,
    16   whitelist: ['navigation'] // navigation会存入缓存,其他不会存,适用于大多数数据并不会实时从后台拿数据
    17 };

      然后在处理reducer时用到persistReducer,一种是直接使用,另一种你可能会使用到combineReducers,接下来就是创建store了,可能会用到中间件,不过此时不要理睬中间件创建store的过程,期间和你之前的创建方式一样,在store创建好的外边,加一句话,然后export里包含persistor就好:

    1 const reducers = persistReducer(persistConfig, reducer);
    2  
    3 const reducers = combineReducers({
    4    depReducer: persistReducer(persistConfig, depReducer)
    5 });
    6 const persistor = persistStore(store);

      最后在ReactDOM.render()的时候引入另一个组件:

     1 import {PersistGate} from 'redux-persist/lib/integration/react';
     2 
     3 ReactDOM.render(
     4   <Provider store={store}>
     5     <PersistGate persistor={persistor}>
     6       <Dep />
     7     </PersistGate>
     8   </Provider>,
     9   document.getElementById('app')
    10 );
  • 相关阅读:
    leetcode Remove Linked List Elements
    leetcode Word Pattern
    leetcode Isomorphic Strings
    leetcode Valid Parentheses
    leetcode Remove Nth Node From End of List
    leetcode Contains Duplicate II
    leetcode Rectangle Area
    leetcode Length of Last Word
    leetcode Valid Sudoku
    leetcode Reverse Bits
  • 原文地址:https://www.cnblogs.com/ljwk/p/9605444.html
Copyright © 2011-2022 走看看