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
相关产品推荐
相关产品推荐

