0

我正在使用这个反应库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 始终为 null

useImperativeHandle 这是包含实现的子页面之一的示例


   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>);
});

关于为什么会发生这种情况的任何想法?

谢谢

4

1 回答 1

0

从您的代码示例中,您实际上并没有渲染您由状态设置器设置的组件:

export default function ParentComponent(props) {
  //...

  // Render the page
  return (
    <>
      {currentPage}
      <div>...</div>
    </>
  );
}
于 2021-12-12T12:04:56.047 回答