我有一个 React 应用程序,其组件包含 iframe。我的组件确实根据状态进行安装和卸载(例如
{(showApp === true) && <MyApp/>}
)。每次安装我的组件时,我的 iframe 都会再次加载,这确实会进行一些额外的网络调用并导致时间增加。有没有办法可以memoize我的组件来防止iframe
再次加载?
这是我的问题的最小可重现示例:
const App1 = () => {
useEffect(() => {
console.log("App1 mounted");
}, []);
return (
<iframe
width="100%"
height="254"
src="https://www.google.com/webhp?igu=1"
></iframe>
);
};
const App2 = () => {
useEffect(() => {
console.log("App2 mounted");
}, []);
return (<div style={{ color: "red" }}>This is App2</div>);
};
const appMap = {
1: <App1 />,
2: <App2 />,
};
const MyApp = ({ app }) => {
const Application = useMemo(() => appMap[app], [app]);
return (
<div>
<span>This is MyApp Container:</span>
{Application}
</div>
);
};
export default function App() {
const [showApp, setShowApp] = useState(null);
const App = useMemo(() => <MyApp app={showApp} />, [showApp]);
return (
<div>
<div onClick={() => setShowApp("1")}>Show App 1</div>
<div onClick={() => setShowApp("2")}>Show App 2</div>
{showApp && App}
</div>
);
}
不涉及“记忆”。你想要做的是永远不要卸载包含 iframe(iframe 本身)的组件,你只是想隐藏它
useMemo 被过度使用了,无论如何它在这里不适用