dva,清除模塊數據


前言:

  在項目中,模塊過多,dva使用namespace分離模塊后,若沒有在模塊卸載后清除對應的數據,下次進入時,有可能會有上一次數據的殘留。

  比如詳情頁,從A商品的詳情頁離開后,返回選擇B商品進入,此時在B商品信息加載之前可能存在A的殘留信息。

  諸如此類,若模塊過多,需要在每個模塊的WillUnmount中去clear又太麻煩。

 

方法:

  在model層擴展。大概思路如下:

  在model-extend.js中配置各種擴展model的[enhanceItems]對象,里面存儲各種擴展model的function,這些function接收來自model的參數,然后返回一個接受model,返回擴展后的model的函數。

  返回上面的需求,在enhanceItems里配置一個enhanceClear,然后監聽路由的變化,在滿足條件的時候,dispatch(clear)

偽代碼:
enhanceItems = {
  enhance1,
  enhance2    
}
enhance1 = (param) => {
   .....//擴展
  return model => newModel  
}

show me the code

// model.js
enhanceModel({
  enhanceClear: {
    reg: /\/detail/,
    clearReducer: { type: 'clearDetail' },
  },
})(model)


// utils/model-extend.js
const enhanceClear = (param) => {
  const { reg, clearReducer } = param;
  if (reg && clearReducer) {
    const clearWrapped = (subscriber) => { // 包裝clearWrapped
      return (props) => {
        const { dispatch, history } = props;
        history.listenBefore(({ pathname }) => { // 監聽跳轉前的動作
          const isout = reg.test(history.getCurrentLocation().pathname)
                && !reg.test(pathname);
          isout && dispatch(clearReducer);
        });
        subscriber({ ...props });
      };
    };
    return (model) => {
    if (!model.subscriptions) model.subscriptions = { setup() {} };
    model.subscriptions.setup = clearWrapped(model.subscriptions.setup || (() => {}));
    return model;
};
  }
  return model => model;// 若沒有相應參數,則返回原數據函數
};

const enhanceItems = {
  enhanceClear,
};
export const enhanceModel = (param) => {
  const enhanceFuns = [];
  Object.keys(param).forEach((key) => {
    enhanceItems[key] && enhanceFuns.push(enhanceItems[key](param[key]));
  });
  return (model) => {
    if (enhanceFuns.length === 0) return model;
    return enhanceFuns.reduce((newModel, fun) => {
      return (typeof fun === 'function') ? fun(newModel) : newModel;
    }, model);
  };
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM