国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 語言 > JavaScript > 正文

重置Redux的狀態(tài)數(shù)據(jù)的方法實(shí)現(xiàn)

2024-05-06 15:43:54
字體:
供稿:網(wǎng)友

在 Redux 使用過程中,通常需要重置 store 的狀態(tài),比如應(yīng)用初始化的時(shí)候、用戶退出登錄的時(shí)候,這樣能夠避免數(shù)據(jù)殘留,避免 UI 顯示了上一個(gè)用戶的數(shù)據(jù),容易造成用戶數(shù)據(jù)泄露。

最簡(jiǎn)單的實(shí)現(xiàn)方法就是為每個(gè)獨(dú)立的 store 添加RESET_APP 的 action,每次需要 reset 的時(shí)候,dispatch 這個(gè) action 即可,如下代碼

const usersDefaultState = [];const users = (state = usersDefaultState, { type, payload }) => { switch (type) {  case "ADD_USER":   return [...state, payload];  default:   return state; }};

添加 reset action 后:

const usersDefaultState = []const users = (state = usersDefaultState, { type, payload }) => { switch (type) {  case "RESET_APP":   return usersDefaultState;  case "ADD_USER":   return [...state, payload];  default:   return state; }};

這樣雖然簡(jiǎn)單,但是當(dāng)獨(dú)立的 store 較多時(shí),需要添加很多 action,而且需要很多個(gè) dispatch 語句去觸發(fā),比如:

dispatch({ type: RESET_USER });dispatch({ type: RESET_ARTICLE });dispatch({ type: RESET_COMMENT });

當(dāng)然你可以封裝一下代碼,讓一個(gè)RESET_DATA 的 action 去觸發(fā)多個(gè) reset 的 action,避免業(yè)務(wù)代碼看上去太亂。

不過本文介紹一種更優(yōu)雅的實(shí)現(xiàn),需要用到一個(gè)小技巧,看下面代碼:

const usersDefaultState = []const users = (state = usersDefaultState, { type, payload }) => {...}

當(dāng)函數(shù)參數(shù) state 為 undefined 時(shí),state 就會(huì)去 usersDefaultState 這個(gè)默認(rèn)值,利用這個(gè)技巧,我們可以在 rootReducers 中檢測(cè) RESET_DATA action,直接賦值 undefined 就完成了所有 store 的數(shù)據(jù)重置。實(shí)現(xiàn)代碼如下:

我們通常這樣導(dǎo)出所有的 reducers

// reducers.jsconst rootReducer = combineReducers({ /* your app's top-level reducers */}) export default rootReducer;

先封裝一層,combineReducers 返回 reducer 函數(shù),不影響功能

// reducers.jsconst appReducer = combineReducers({ /* your app's top-level reducers */})const rootReducer = (state, action) => { return appReducer(state, action)}export default rootReducer;

檢測(cè)到特定重置數(shù)據(jù)的 action 后利用 undefined 技巧 (完整代碼)

// reducers.jsconst appReducer = combineReducers({ /* your app's top-level reducers */})const rootReducer = (state, action) => { if (action.type === 'RESET_DATA') {  state = undefined } return appReducer(state, action)}

參考:

Resetting Redux State with a Root Reducer
How to reset the state of a Redux store?

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持錯(cuò)新站長(zhǎng)站。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 大丰市| 个旧市| 泰来县| 军事| 宁城县| 吐鲁番市| 潞西市| 彝良县| 同江市| 万安县| 宣城市| 大竹县| 和顺县| 丰镇市| 永清县| 财经| 合山市| 永康市| 普兰县| 台安县| 灯塔市| 兴业县| 西乌珠穆沁旗| 松原市| 黄冈市| 耿马| 洪湖市| 达州市| 准格尔旗| 兴城市| 五原县| 宝清县| 固始县| 海安县| 建宁县| 汝南县| 临邑县| 绥德县| 凉山| 丰顺县| 本溪市|