React Dva 操作models中的subscriptions讲述监听

接下来 我们来看一个models的属性
之前没有讲到的subscriptions

我们可以在自己有引入的任意一个models文件中这样写

subscriptions: {
    
    
    setup({
     
      dispatch, history }) {
    
    
        console.log(dispatch);
    },
},

在这里插入图片描述
这样 一进来 这个位置就会触发
在这里插入图片描述
这里 我们可以写多个

subscriptions: {
    
    
    setup({
     
      dispatch, history }) {
    
    
        console.log(dispatch);
    },
    mingt({
     
      dispatch, history }) {
    
    
        console.log("你好");
    }
},

然后 我们运行后会发现 他们都是可以触发的
在这里插入图片描述
这里 我们可以用它来监听一些东西 然后触发我们models中的函数
例如

setup({
     
      dispatch, history }) {
    
    
  window.onresize = () => {
    
    
        dispatch({
    
    
            type: "AsynchSchedul/getAsynchSchedulList",
            payload: {
    
    
                id: 123
            }
        }).then(res => {
    
    
            console.log(res);
        })
    }
},

在这里插入图片描述
这里 我们监听屏幕变化 window中的onresize事件
然后 我们拖动F12 改变界面宽度 这样 这个事件就会一直触发去请求
在这里插入图片描述
但是 其实我不建议大家这样去写 因为多次请求性能不好 很容易程序崩溃
但操作一下基本数据 或者特殊需求 就需要你调 接口 那也可以这样去写

我们也可以改成这样

subscriptions: {
    
    
     setup({
     
      dispatch, history }) {
    
    
        history.listen((location) =>{
    
    
            console.log(location);
        })
    },
    
},

运行结果如下
在这里插入图片描述
老实说 个人感觉这个东西作用并不大 有点鸡肋 知道有这么个东西就好了

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/132140774
今日推荐