微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决在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 举报,一经查实,本站将立刻删除。