Javascript 在react and close弹出窗口中从eventListener分派事件
我对react还是新手,我正在尝试在react中的响应中调用Javascript 在react and close弹出窗口中从eventListener分派事件,javascript,reactjs,addeventlistener,dispatch,Javascript,Reactjs,Addeventlistener,Dispatch,我对react还是新手,我正在尝试在react中的响应中调用dispatch(),但页面从未停止加载,如下面的快照所示 这是我的密码 profile/index.jsx profile/operations.js 下面是服务器端的响应示例。我通过将下面代码中的profile或error变量传递给客户端进行测试: handleCallback.js 错误: 因此,我对这段代码没有什么问题: 弹出窗口有时会在新选项卡中打开,而不是弹出窗口 控制台中充斥着快照中的上述消息 在saveProfile中
dispatch()
,但页面从未停止加载,如下面的快照所示
这是我的密码
profile/index.jsx
profile/operations.js
下面是服务器端的响应示例。我通过将下面代码中的profile
或error
变量传递给客户端进行测试:
handleCallback.js
错误:
因此,我对这段代码没有什么问题:
为什么要收听名为“message”的窗口事件?这似乎是一个非常具体但同时又很常见的事件名称(可能是浏览器本机使用的?)您是否尝试使用更具体的名称?我没有。因为看起来event.type是一条消息。你觉得我应该用哪种?我不知道。。。在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}`;
};
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
}
}
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",
"statusCode": 500,
"code": 1004
}