由于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;