2024-06-08 渥太华微生活
采用 MUI Data Grid 在 React 中显示后端数据
1、安装后台并准备数据:
1) 安装应用:
composer create-project --prefer-dist laravel/laravel laravel-react-mui-datagrid
2) 模拟数据:
修改 database\seeders\DatabaseSeeder.php 文件:
<?php namespace Database\Seeders; use App\Models\User; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. */ public function run(): void { User::factory(20)->create(); } }
运行下面命令产生用户数据:
php artisan db:seed
3) 安装API:
使用下面一个命令将安装Sanctum的扩展包、配置和迁移文件,并添加API路由。
php artisan install:api
4) 修改API路由:
修改 routes\api.php 文件
<?php use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; Route::get('/users', function (Request $request) { return User::all(); });
5) 检查API返回结果:
通过下面命令启动本地服务器
php artisan serve
访问 http://127.0.0.1:8000/api/users,API返回结果如下(20条用户数据):
2、安装前台并显示数据:
1) 安装 react, react-dom,@vitejs/plugin-react 和 axios:
npm install react react-dom @vitejs/plugin-react axios @mui/material @emotion/react @emotion/styled @mui/x-data-grid
2) 更新 vite.config.js:
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [ laravel({ input: ['resources/css/app.css', 'resources/js/app.jsx'], refresh: true, }), react(), ], });
3) 更新主页(单页面SPA):
<!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>React Test</title> @viteReactRefresh @vite('resources/js/app.jsx') </head> <body> <div id="app"></div> </body> </html>
4) 用 resources/js/app.jsx 代替 resources/js/app.js:
import './bootstrap'; import '../css/app.css' import ReactDOM from 'react-dom/client'; import Home from './pages/Home'; ReactDOM.createRoot(document.getElementById('app')).render(<Home />)
5) 创建数据显示的页面:
resources\js\pages\Home.jsx
import { DataGrid } from "@mui/x-data-grid"; import axios from "axios"; import { useEffect, useState } from "react"; export default function Home() { const BASE_URL = 'http://127.0.0.1:8000'; const [tableData, setTableData] = useState([]); const columns = [ {field: 'id', headerName: 'ID', width: 10}, {field: 'name', headerName: 'Name', width: 200}, {field: 'email', headerName: 'Email', width: 200}, {field: 'email_verified_at', headerName: 'email_verified_at', width: 200}, {field: 'created_at', headerName: 'created_at', width: 200}, {field: 'updated_at', headerName: 'updated_at', width: 200} ]; useEffect(() => { axios.get(`${BASE_URL}/api/users`).then(response => { setTableData(response.data); }).catch(error => { console.log(error); }); }, []); return ( <div style={{ height: 500, width: '100%' }}> <DataGrid rows={tableData} columns={columns} /> </div> ); }
通过下面命令启动 Vite 服务器
npm run dev
访问 http://127.0.0.1:8000/,显示结果如下(20条用户数据):
编者注:新闻取自各大新闻媒体,新闻内容并不代表本网立场!文字和图片来自网络,版权归原作者所有。如有侵权,请速联系小编,立即删除。
全部评论 (0) |
---|