【发布时间】:2022-01-16 05:31:10
【问题描述】:
我正在使用这个反应库 https://github.com/gregberge/loadable-components 加载一个带有 Ref 的组件,以使用 useImperativeHandle 访问实例值,但 ref 始终为空。
这是我的代码
import loadable from '@loadable/component';
export default function ParentComponent(props){
const currentPageRef = useRef();
const[currentPage,setCurrentPage]=useState();
const loadPage= (page= 'home') => {
const CurrentPage = loadable(() => import(`./${page}`));
return (
<CurrentPage
ref={currentPageRef}
/>
);
}
useEffect(() => {
console.log(currentPageRef); //This is always logging current(null);
let pageTitle= currentPageRef.current?.getTitle();
let pageSubTitle= currentPageRef.current?.getSubTitle();
console.log(` Page Title=${pageTitle}`); //This is always coming back as null
console.log(`Page SubTitle=${pageSubTitle}`); //This is also always coming back as null
}, [currentPage]);
return (
<div>
<button onClick={() => {
setCurrentPage(loadPage('youtube));
}}>
LoadPage
</button>
</div>
);
}
每个子组件都包含一个 useImperativeHandle 以公开实例函数,但我似乎无法访问任何函数,因为 currentPageRef 始终为空
这是包含useImperativeHandle implementation 的子页面之一的示例
const YouTubePage= React.forwardRef((props,ref)=>{
const [connected, setConnected] = useState(false);
const getTitle = () => {
return connected ? "Your YouTube Channels" : "YouTube";
}
const getSubTitle = () => {
return connected ? "Publishable content is pushed to only connected channels. You may connect or disconnect channel(s) as appropriate" : "Connect a YouTube account to start posting";
}
useImperativeHandle(ref, () => ({ getTitle, getSubTitle }));
return (<div></div>);
});
关于为什么会发生这种情况的任何想法?
谢谢
【问题讨论】:
-
延迟安装而不是正常的条件渲染背后的原因是什么。您应该尝试条件渲染。
-
条件渲染需要大量代码。我追求高效且最少的代码行
标签: reactjs loadable-component