react-pdf throwing 渲染了比上一次渲染更多的钩子

react-pdf throwing Rendered more hooks than during the previous render

我正在实施 react-pdf 以在网络视图中显示 pdf。如果有任何帮助,React 应用程序可与 Typescript 和 Next 一起使用。

到目前为止,这是我的代码

const MyPage: NextPage = () => {
// some code here
  const [numPages, setNumPages] = useState(null);
  const onDocumentLoadSuccess = (numPages:any) =>  {
      setNumPages(numPages);
    }
  return (
    <>
          <div className="white-background">
            <hr />
            <div className="pdf-container">
              <Document
                file={data?.pdf}
                options={{ workerSrc: "/pdf.worker.js" }}
                onLoadSuccess={onDocumentLoadSuccess}
              >
                {Array.from(new Array(numPages), (el, index) => (
                  <Page key={`page_${index + 1}`} pageNumber={index + 1} />
                ))}
              </Document>
              <p>
                Page {pageNumber} of {numPages}
              </p>
            </div>
            
          <hr/>
          </div>

   </>

就我而言,我按照与文档相同的方式使用该组件,但它抛出了这个错误 ->

Uncaught Error: Rendered more hooks than during the previous render.

指向const [numPages, setNumPages] = useState(null); 特别是 useState(null)

我坚信问题出在调用 onLoadSuccess={onDocumentLoadSuccess} 上,因为该函数正在调用对钩子的引用,并且每当它 returns 它在页面中加载一个额外的钩子时,就会抛出错误。

那么问题是 onLoadSuccess 需要一个引用而不是一个函数

我已经尝试过使用括号 () 传递,但它会引发错误。所以目前还没有任何线索。

知道如何解决吗?

问题是我在放置

const [numPages, setNumPages] = useState(null);

在我的函数组件中的一个条件之后。我把它放在最上面,问题就解决了。