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

React类组件中如何替代Inertiajs usePage()获取服务端数据?

在React类组件中获取Inertia.js服务端传递的数据

在React类组件里,你可以用Inertia.js提供的withPage高阶组件来替代函数组件中的usePage钩子,具体实现方式如下:

  • 从@inertiajs/react导入withPage高阶组件
  • 用withPage包裹你的类组件,它会自动将page对象注入到组件的props中
  • 通过this.props.page.props即可访问服务端传递过来的数据

示例代码:

import { withPage } from '@inertiajs/react';
import React from 'react';

class Layout extends React.Component {
  render() {
    // 从注入的page对象中获取服务端传递的auth数据
    const { auth } = this.props.page.props;

    return (
      <main>
        <header>
          你当前登录的账号是:{auth.user.name}
        </header>
        <content>
          {this.props.children}
        </content>
      </main>
    );
  }
}

// 用withPage包裹组件后导出
export default withPage(Layout);

withPage注入的page对象和usePage()返回的结构完全一致,你可以按照同样的逻辑访问共享数据、当前路由信息等内容。

内容的提问来源于stack exchange,提问作者Han Tran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:37:11