如何在Inertia React的导航页面中获取认证用户信息
在Inertia React中获取认证用户信息的方法
在Inertia React中无法直接使用Vue里的$page.props.auth.user语法,因为React版本遵循React Hooks规范,需要通过**usePage钩子**来获取页面props,具体实现如下:
- 首先导入Inertia提供的
usePage钩子:
import { usePage } from '@inertiajs/react'
- 在组件中解构认证用户信息:
你可以选择分步解构或一次性解构,两种方式均有效:
- 分步解构(可读性更强):
const page = usePage(); const auth = page.props.auth; const user = auth.user;
- 一次性解构(更简洁):
const { props: { auth: { user } } } = usePage();
- 导航组件中的实际使用示例:
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
相关产品推荐
相关产品推荐

