You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React类组件使用useState报错Invalid hook call的解决方法

解决React类组件中Invalid hook call错误的方案

Hey there! Let's fix that hook call error you're running into. The core issue here is that React Hooks (like useState) can only be called at the top level of function components or custom Hooks—you're currently trying to use useState inside a method of a class component, which breaks React's rules for Hooks.

Here are two solid solutions to get your PDF viewer working:

方案1:改用函数组件(推荐)

React now strongly recommends function components paired with Hooks for most use cases, and this will simplify your code a lot. Here's how to refactor your component:

import { Document, Page } from 'react-pdf';
import { useState } from 'react';

// 转换为函数组件
const PdfViewer = () => {
  // 将useState放在函数组件的顶层(符合Hook规则)
  const [numPages, setNumPages] = useState(null);
  const [pageNumber, setPageNumber] = useState(1);

  return (
    <div>
      <Document 
        file={eggPdf} 
        onLoadSuccess={({ numPages }) => {
          setNumPages(numPages);
        }}
      >
        <Page pageNumber={pageNumber} />
      </Document>
      <p>Page {pageNumber} of {numPages}</p>
    </div>
  );
};

export default PdfViewer;

This removes the unnecessary pdfView method and render method, moving your state management directly to the top of the function component where Hooks belong.

方案2:保留类组件,改用类的state管理

If you prefer sticking with class components, you can use the class-based state system instead of Hooks. Here's the adjusted code:

import { Document, Page } from 'react-pdf';
import { Component } from 'react';

class PdfViewer extends Component {
  // 初始化类组件的state
  state = {
    numPages: null,
    pageNumber: 1
  };

  // 处理PDF加载成功的回调
  handlePdfLoad = ({ numPages }) => {
    this.setState({ numPages });
  };

  render() {
    const { numPages, pageNumber } = this.state;
    return (
      <div>
        <Document 
          file={eggPdf} 
          onLoadSuccess={this.handlePdfLoad}
        >
          <Page pageNumber={pageNumber} />
        </Document>
        <p>Page {pageNumber} of {numPages}</p>
      </div>
    );
  }
}

export default PdfViewer;

Here, we use the class's built-in state property and this.setState method to manage your page state, which is the standard way to handle state in class components.

Either approach will resolve the "Invalid hook call" error. The function component option is generally preferred these days as it leads to more concise and maintainable code.

内容的提问来源于stack exchange,提问作者Yige Song

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 10:07:53