namespace: 'global',

state: {
  collapsed: false,
  notices: [],
},

reducers: {
     saveNoticesWebsock(state, { payload }): GlobalModelState {//此处可以根据自己的业务写
      let dd=[...payload,...state.notices];
      console.log(dd,"saveNoticesWebsock")
      return {
        collapsed: false,
        ...state,
        notices: dd,
      };
    },
},

subscriptions: {
    setup({ dispatch,history }): void {
      
      // Subscribe history(url) change, trigger `load` action if pathname is `/`
      history.listen(({ pathname, search }): void => {
        if (typeof window.ga !== 'undefined') {
          window.ga('send', 'pageview', pathname + search);
        }
        if (!pathname.indexOf('/welcome')) {
          const ws = new WebSocket('ws://127.0.0.1:1234/websocket');
          ws.onmessage = function(msg) { 
            console.log('接收服务端发过来的消息', msg); 
            // result += msg.data + '\n'; 
            dispatch({
              type: 'saveNoticesWebsock', 
              payload: JSON.parse(msg.data),
            });
          }; 
          ws.onclose = function (e) {
              console.log('ws 连接关闭了');
          }
        }
      });
    }
  },

本文由 吾爱 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论