React 集成
本节按“能跑起来”为目标,给出最小接入步骤。
安装
$ npm i @midwayjs/react @midwayjs/web-bridge @midwayjs/mock
{
"dependencies": {
"@midwayjs/react": "^4.0.0",
"@midwayjs/web-bridge": "^4.0.0",
"@midwayjs/mock": "^4.0.0"
}
}
1. 创建客户端
// src/web/api/client.ts
import { createClient } from '@midwayjs/web-bridge';
import { userApi } from '../../server/api/user.api';
export const api = createClient(
{ user: userApi },
{ basePath: '/api' }
);
2. 在页面里调用
import { useEffect, useState } from 'react';
import { api } from './api/client';
export function UserPage() {
const [name, setName] = useState('');
useEffect(() => {
api.user.getUser({ params: { id: 'u-1' } }).then(user => {
setName(user.name);
});
}, []);
return <div>{name}</div>;
}