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

如何在Inertia React的导航页面中获取认证用户信息

在Inertia React中获取认证用户信息的方法

在Inertia React中无法直接使用Vue里的$page.props.auth.user语法,因为React版本遵循React Hooks规范,需要通过**usePage钩子**来获取页面props,具体实现如下:

  1. 首先导入Inertia提供的usePage钩子:
import { usePage } from '@inertiajs/react'
  1. 在组件中解构认证用户信息:
    你可以选择分步解构或一次性解构,两种方式均有效:
  • 分步解构(可读性更强):
const page = usePage();
const auth = page.props.auth;
const user = auth.user;
  • 一次性解构(更简洁):
const { props: { auth: { user } } } = usePage();
  1. 导航组件中的实际使用示例:
import { usePage } from '@inertiajs/react'

export default function Navigation() {
  const { props: { auth: { user } } } = usePage();

  return (
    <nav className="navigation-bar">
      <span>欢迎回来,{user.name}</span>
      {/* 其他导航内容,比如退出登录按钮、用户菜单等 */}
    </nav>
  );
}

差异说明

Inertia Vue通过全局注入的$page对象共享页面props,而React版本则贴合React的设计模式,用usePage钩子来获取这些全局数据,这是两个框架版本的核心区别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 20:39:51