react 如何使用reducer ?

由于react 組件化,跨組件傳遞數(shù)據(jù)往往不是很方便,于是就考慮數(shù)據(jù)共享。
例如,商品列表,選擇商品后,通過添加,刪除控制在右側(cè)顯示已選擇的角色。點(diǎn)擊下方的按鈕區(qū)域,傳遞已選擇商品數(shù)據(jù)。
該類型可以考慮使用react hooks 的useReducer。
但是useReducer 通過自定義,才能有更好的使用效果。

以商品列表為例,商品列表的初始數(shù)據(jù)需要從接口獲取,這個(gè)適合可以寫一個(gè)函數(shù)接收該數(shù)據(jù)作為參數(shù),然后將數(shù)據(jù)作為依賴的形式。利用依賴觸發(fā)(dispatch)初始的action。

使用方式如下:
組件associateProduct.js
import?useSelectedProductReducer?from?'../hooks/useSelectedProductReducer';
const?selectedProductCodesByRequest?=?useMemo(()?=>?{? ? ? ? ????return?selectedProductsByRequest.reduce((pre,next)?=>?{
? ? ? ? ? ? pre.push(next.productCode);
????? ? ? ? ? ? return?pre;
????? ? ? ? },[]);? ?
},[selectedProductsByRequest]);? // selectedProductsByRequest?通過接口獲取作為依賴
const?[selectedProductCodes,dispatch]?=?useSelectedProductReducer(selectedProductCodesByRequest);

useSelectedProductReducer.js代碼如下:
import?React,?{?useReducer,useEffect?}?from?'react';
const?reducer?=?(state,?{?type,?payload?})?=>?{
? ? switch?(type)?{
????? ? case?'add':
????? ? ? ? return?[...state,?...payload];
????? ? case?'remove':
????? ? ? ? return?state.filter((productCode)?=>?!payload.includes(productCode));
????? ? default:
????? ? ? ? return?[...payload];
????? ? }
};

function?useSelectedProductReducer(depData)?{
? ? const?[selectedProductCodes,?dispatch]?=?useReducer(reducer,[]);
? ? useEffect(()?=>?{
? ? ? ? if(depData)?{
? ? ? ? ? ? dispatch({
? ? ? ? ? ? ? ? type:'default',
? ? ? ? ? ? ? ? payload:?depData
? ? ? ? ? ? });
? ? ? ? }
? ? },[depData]);
? ? return??[selectedProductCodes,?dispatch];
}

export?default?useSelectedProductReducer;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 最新在學(xué)ReactHooks這個(gè)新特性,把學(xué)習(xí)筆記記下來,供大家分享。 原先的函數(shù)組件是沒有生命周期函數(shù)的,這樣在...
    番茄_tomatoMan閱讀 1,829評論 0 0
  • react hooks demo 創(chuàng)建所需要的組件,這個(gè)項(xiàng)目我們分成三個(gè)組件, 分別是頭部,搜索框,電影列表// ...
    Joemoninni閱讀 785評論 0 3
  • 一、react新特性 1. context 在一個(gè)典型的 React 應(yīng)用中,數(shù)據(jù)是通過 props 屬性自上而下...
    zxhnext閱讀 1,111評論 0 0
  • 關(guān)于React Hook React Hook 對于React來說無疑是一個(gè)偉大的特性,它將React從類組件推向...
    Mstian閱讀 2,464評論 0 11
  • React Hooks 在了解React Hooks之前, 我們先看一下 Class 和函數(shù)式 的一般寫法 Cla...
    YM雨蒙閱讀 2,967評論 0 1

友情鏈接更多精彩內(nèi)容