zoukankan      html  css  js  c++  java
  • 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);
      };
    };
  • 相关阅读:
    《就这》
    《我傻了》
    nginx配置本地https方法
    idea插件开发——Generate Resource SQL
    Java本地命令执行
    自定义类加载器和UrlClassLoader
    类加载器学习
    IO流学习
    Java
    static关键字
  • 原文地址:https://www.cnblogs.com/laojun/p/9115494.html
Copyright © 2011-2022 走看看