gpt4 book ai didi

javascript - React hooks 改变 postMessage 的状态

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:23:30 25 4
gpt4 key购买 nike

我有一个使用 useState 的组件。

此组件打开一个新选项卡,并应在 postMessage 上接收消息事件。由于某种原因,在我获得事件后,状态返回到其初始状态。

我尝试将状态保存到 localStorage 并且成功了。

索引.js

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

const App = () => {
const [state, setState] = useState("hello");

const onClick = () => {
setState("world");
window.open("tab.html");
};

const onMessageReceivedFromIframe = event => {
console.log("onMessageReceivedFromIframe", state, event);
};

const addIframeListener = () =>
window.addEventListener("message", onMessageReceivedFromIframe);
const removeIframeListener = () =>
window.removeEventListener("message", onMessageReceivedFromIframe);

useEffect(() => {
addIframeListener();
return () => {
removeIframeListener();
};
}, []);

useEffect(() => {
console.log("Current state: ", state);
}, [state]);

return <button onClick={onClick}>Click here</button>;
};

ReactDOM.render(<App />, document.getElementById("app"));

tab.html

<html>
<body>
tab
<script>
setTimeout(() => {
console.log("post");
window.opener.postMessage("some message", "https://9jzj7.csb.app");
window.close();
}, 2000);
</script>
</body>
</html>

状态回到初始状态。

可以在这里看到一个演示: https://codesandbox.io/s/trusting-waterfall-9jzj7

顺便说一句:我知道该事件不是从 tab.html 触发的,但仍有一个事件会在打开选项卡时触发。

最佳答案

您的问题似乎出在效果 Hook 的 deps 数组上,并且在每次渲染时都会创建 onMessageReceivedFromIframe。下面的解决方案应该像您期望的那样工作。这是 codesandbox 的链接

const App = () => {
const [state, setState] = useState("hello");

const onClick = () => {
setState("world");
console.log(state);
window.open("tab.html");
};

const onMessageReceivedFromIframe = React.useCallback(
event => {
console.log("onMessageReceivedFromIframe", state, event);
},
[state]
);

useEffect(() => {
window.addEventListener("message", onMessageReceivedFromIframe);
return () =>
window.removeEventListener("message", onMessageReceivedFromIframe);
}, [onMessageReceivedFromIframe]);

React.useEffect(() => {
console.log("state", state);
}, [state]);

return <button onClick={onClick}>Click here</button>;
};

关于javascript - React hooks 改变 postMessage 的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57303504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com