在react和close弹出窗口中从eventListener调度事件

问题描述

我仍然是个新手,我想在响应中调用dispatch(),但是该页面从未停止加载,如下面的快照所示。

这是我的代码...

profile / index.jsx

import { usedispatch } from 'react-redux';
import {profileOperations} from "state/profile";

const dispatch = usedispatch();
const openPopup = () => {
    const popupWindow = window.open('',POPUP_WINDOW,windowParams);
    attachEvent(popupWindow);
};

const attachEvent = popupWindow => {
    window.addEventListener(
         'message',function(event){
               if (event.data &&
                   typeof event.data !== 'undefined') {             
                   dispatch(profileOperations.saveProfile(event));
                   popupWindow.close();
               }
         },false
    );
);

const windowParams = () => {
   const threeDSPopupHeight = 500;
   const threeDSPopupWidth = isMobileDevice ? 360 : 600;
   const popupLeftPosition = leftPosition(threeDSPopupWidth);
   const popupTopPosition = topPosition(threeDSPopupHeight);
   return `resizable=yes,toolbar=no,screenX=${popupLeftPosition},screenY=${popupTopPosition},menubar=no,scrollbar=yes,width= ${threeDSPopupWidth},height=${threeDSPopupHeight},top= ${popupTopPosition},left=${popupLeftPosition}`;
};

profile / operations.js

export const saveProfile = event => dispatch => {
    try {
        const response  = JSON.parse(event.data);
        if (response.profiles) {
            dispatch(processprofile(response));
        } else if(response.statusCode){
            console.log('body contains error');
            dispatch(resourceErrorHandler(response))
        }
    } catch {
        // do nothing
    }
}

这是服务器端的示例响应。我通过将以下代码中的profileerror变量传递给客户端进行测试:

handleCallback.js

module.exports = ({ error,response = {},body },res) => {
    const profile = '{"profiles":[{"id":"515592671","token":"8416003642718270"}]}';
    const error = '{"message": "Internal Error with browser","statusCode": 500,"code": 1004}';
    res.send("<script type=\"text/javascript\">"
        +  "const data = "+JSON.stringify(profile)+";"
        + " window.opener.postMessage(data,\"http://localhost\");"
        + "</script>");
};

成功:

{
    "profiles": [{
        "id": "515592671","token": "8416003642718270"
    }]
}

错误

{
    "message": "Internal Error with browser","code": 1004
}

enter image description here

因此,我在这代码中遇到了一些问题:

  1. 弹出窗口有时会在新选项卡中打开,而不是在弹出窗口中打开
  2. 控制台中的快照中充满了以上消息
  3. 将所有内容加载到saveProfile后,弹出窗口应关闭
  4. 如何将事件监听器限制为仅监听上述成功/错误响应

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)