在React的useEffect中动态加载组件后无法渲染问题求助
解决React useEffect动态加载组件的问题
你的代码里有几个关键问题导致组件无法正确渲染,下面逐个修正:
1. 动态导入的参数与导出获取错误
import()返回的是包含模块导出的对象,默认导出需要通过.default获取,同时你在then回调里用了未定义的result变量,应该用回调的参数名。
2. 组件导出拼写错误
preFooterPage.js里组件定义是PreFooterPage,但导出写的是PreFooterPages,多了个s,导致导入后找不到正确组件。
3. React组件命名规范
React要求组件首字母必须大写,所以存组件的状态变量名建议改成首字母大写,渲染时也要用大写开头的变量。
修正后的主文件(footer.js)
import React, { useEffect, useState} from "react"; const MyMainComponent = ({ type }) => { // 状态变量名首字母大写,符合组件规范 const [PreFooter, setPreFooter] = useState(null) useEffect(() => { if (type === "page") { import("./prefooter/preFooterPage") // 获取默认导出,修正参数名 .then(module => setPreFooter(module.default)); } else { import("./prefooter/preFooterArticle") .then(module => setPreFooter(module.default)); } }, [type]); return ( <div> {/* 组件存在时再渲染,避免null渲染报错 */} {PreFooter && <PreFooter />} </div> ) } export default MyMainComponent
修正后的preFooterPage.js
import React from "react"; const PreFooterPage = () => { return ( <h2>Hi, I'm a pre Footer for pages !</h2> ) } // 修正导出名,和组件名一致 export default PreFooterPage
preFooterArticle.js无需修改,保持原样
import React from "react"; const PreFooterArticle = () => { return ( <h2>Hi, I'm a pre Footer for blog posts !</h2> ) } export default PreFooterArticle
这样修改后,当type变化时,就能正确加载对应的组件并渲染了。
内容的提问来源于stack exchange,提问作者Arthur Fortin
相关产品推荐
相关产品推荐

