使用React createContext后子组件全部无法渲染如何排查解决
问题根因排查与修复方案
核心错误1:children拼写错误(直接导致组件不渲染)
你在MentorsProvider的返回值中,错误将props.children拼写为props.childern,导致Context Provider没有正确渲染包裹的所有子组件,这是启用Context后页面无内容的直接原因。
修复方法:将MentorsContext.js中对应行替换为:
{props.children}
核心错误2:异步请求逻辑错误
你定义的getMentors异步请求函数,调用位置写在了函数自身内部,一旦触发就会进入无限递归调用;同时你没有在useEffect的顶层作用域调用该函数,页面初始加载时永远不会发起数据请求。
修复方法:调整useEffect内的逻辑,把getMentors()移到函数外部:
useEffect(() => { const getMentors = async () => { try { const res = await fetch("http://localhost:3001/mentors"); const data = await res.json(); //console.log(data); setMentors(data); } catch (err) { console.log(err); } }; // 顶层调用触发初始请求 getMentors(); }, []);
内容的提问来源于stack exchange,提问作者Zed
相关产品推荐
相关产品推荐

