react 动态加载组件
<p>有很多组件、根据类型不同,希望能够动态加载对应的组件。</p><p>现在的做法是,通过if else 或者switch 去渲染,但是这些组件都是一次性的全部加载进来了。</p>
<p>这样要写很多重复代码 ,想的思路是 通过 路径 传进去 ,找到 路径 对应的组件 作为变量 放到 dom 里面</p>
<p>实现方式</p>
<pre><code>const DevicePage: React.FC<props> = ({ children }) => {
const rightPanelEnum = useRecoilValue(rightPanelType);
const = useState<ReactNode | null>(null);
useEffect(() => {
// 根据 rightPanelEnum 不同,加载不同的 组件文件
import(`@/compoments/inputSlotAttribute/${rightPanelEnum}`).then(({ default: Component }) => {
setComponent(Component);
});
}, );
return (
<div className="inner-content">
<div className="content-right">
{/* 动态加载*/}
{Component ? component : null}
</div>
</div>
);
};
export default DevicePage;
</code></pre>
<h1 id="遇到的问题">遇到的问题</h1>
<p>如果你 组件路径 没有写错的话 ,可能会遇到这种问题</p>
<pre><code>Warning: Do not call Hooks inside useEffect(...), useMemo(...), or other built-in Hooks. You can only call Hooks at the top level of your React function. For more information, see https://reactjs.org/link/rules-of-hooks
</code></pre>
<p>他说你 在 useEffect 或者 useMemo 里面 调用 了hook ,这个是不被允许的</p>
<p>https://zh-hans.reactjs.org/warnings/invalid-hook-call-warning.html</p>
<p>如果你传一个素的组件, 他就不会报这个错, 页面 也会被正常显示出来<br>
<img src="https://img2022.cnblogs.com/blog/1801618/202207/1801618-20220707210331460-1439397529.png"></p>
<p>但是你在素组件里面 加了 useState 啊 ,useEffect 啊 等 hooks 的话, 他就报错了</p>
<p><img src="https://img2022.cnblogs.com/blog/1801618/202207/1801618-20220707210402346-1572172353.png"></p>
<p>解决办法就是你 可以 在素组件里面 放你 想要 动态 改变的组件,即使 动态改变的组件里面 有 hooks 也不受影响</p>
<h1 id="参考">参考</h1>
<p>js import https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/import</p><br><br>
来源:https://www.cnblogs.com/ifnk/p/16456127.html
頁:
[1]