【问题标题】:Ref always return null in Loadable ComponentRef 在可加载组件中总是返回 null
【发布时间】: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


【解决方案1】:

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

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

  // Render the page
  return (
    <>
      {currentPage}
      <div>...</div>
    </>
  );
}

【讨论】:

  • 我做到了。我没有显示那部分代码。对此感到抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-24
  • 2021-09-16
  • 2015-12-03
  • 2019-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多