前言
redux-smooth-storage
是一个使用 Redux 实现本地存储的 npm 包。通过它,我们可以将 Redux 的状态储存到本地,以便在下次打开页面时能够恢复状态。本文将详细介绍如何使用 redux-smooth-storage
。
准备工作
首先,需要安装 redux-smooth-storage
。可以通过 npm 进行安装:
npm install redux-smooth-storage
使用方法
1. 配置存储
在 Redux 中使用 redux-smooth-storage
前,需要对存储进行配置。可以使用 redux-smooth-storage
的 configureStorage
方法来进行配置。
import { configureStorage } from 'redux-smooth-storage'; const storageConfig = { whitelist: ['key'], storageType: localStorage }; const storage = configureStorage(storageConfig);
whitelist
参数用于指定哪些状态需要进行本地存储,只有包含在 whitelist
中的状态才会被进行存储。
storageType
用于指定存储类型,localStorage
或 sessionStorage
可以指定。如果要使用自定义存储类型,则需要设置自定义存储实例。
2. 调用中间件
与其他 Redux 中间件一样,使用 applyMiddleware
引入 redux-smooth-storage
。
import { createStore, applyMiddleware } from 'redux'; import { middleware } from 'redux-smooth-storage'; import rootReducer from './reducers'; const store = createStore( rootReducer, applyMiddleware(middleware(storage)) );
middleware
方法需要传入 storage
对象,其中包含了之前配置的存储参数。
3. 完成,开始使用
现在,状态已经可以被存储到本地了。我们可以像平常一样,通过 getState
来获取状态。
import store from './store'; console.log(store.getState());
示例代码
下面是一个使用 redux-smooth-storage
的完整示例。
-- -------------------- ---- ------- -- --- ------ - ---------------- - ---- ----------------------- ------ - ---------- - ---- ----------------------- ------ - ------------ --------------- - ---- -------- -- ---- ----- ------------- - - ---------- ------------ ------------ ------------ -- ----- ------- - -------------------------------- -- -- ------- ----- ------------ - - -------- - -- -------- ------------- - ------------- ------- - ------ ------------- - ---- ------------ ------ - --------- -------- ------------- - - -- ---- ------------ ------ - --------- -------- ------------- - - -- -------- ------ ------ - - -- -- ----- ----- ----- - -------------------- -------------------------------------- -- ------ ------------------ -- - ------------------------------ --- -- -- ------ ---------------- ----- ----------- --- ---------------- ----- ----------- --- ---------------- ----- ----------- ---
总结
通过配置 redux-smooth-storage
,我们可以将 Redux 的状态储存在本地,以便在下次使用时进行恢复。当你需要开发一个需要本地存储状态的应用时,redux-smooth-storage
是一个非常好的选择。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/60067008e361a36e0bce8b9a