如何將 React 與 Deno 搭配使用
React 是使用最廣泛的 JavaScript 前端框架。它推廣了使用反應式資料模型,以宣告方式設計使用者介面的方法。由於其受歡迎程度,在使用 Deno 建置網路應用程式時,它是最受要求的框架,這一點也不令人意外。
本教學課程將引導您在不到五分鐘的時間內使用 Deno 建置一個簡單的 React 應用程式。此應用程式將顯示恐龍清單。當您按一下其中一個恐龍時,它會帶您到一個包含更多詳細資料的恐龍頁面。
建立 Vite Extra
本教學課程將使用 Vite 快速建立 Deno 和 React 應用程式架構。讓我們執行
deno run --allow-env --allow-read --allow-write npm:create-vite-extra
我們將專案命名為「dinosaur-react-app」。然後,cd
進入新建立的專案資料夾。
新增後端
下一步是新增後端 API。我們將建立一個非常簡單的 API,用來傳回恐龍的資訊。
在目錄中,讓我們建立一個 api
資料夾。在該資料夾中,我們將建立一個 main.ts
檔案,它將執行伺服器,以及一個 data.json
,這是硬式編碼的資料。
mkdir api && touch api/data.json && touch api/main.ts
將 此 json 檔案 複製並貼到您的 api/data.json
中。
然後,讓我們更新 api/main.ts
import { Application, Router } from "https://deno.land/x/oak@v11.1.0/mod.ts";
import { oakCors } from "https://deno.land/x/cors@v1.2.2/mod.ts";
import data from "./data.json" assert { type: "json" };
const router = new Router();
router
.get("/", (context) => {
context.response.body = "Welcome to dinosaur API!";
})
.get("/api", (context) => {
context.response.body = data;
})
.get("/api/:dinosaur", (context) => {
if (context?.params?.dinosaur) {
const found = data.find((item) =>
item.name.toLowerCase() === context.params.dinosaur.toLowerCase()
);
if (found) {
context.response.body = found;
} else {
context.response.body = "No dinosaurs found.";
}
}
});
const app = new Application();
app.use(oakCors()); // Enable CORS for All Routes
app.use(router.routes());
app.use(router.allowedMethods());
await app.listen({ port: 8000 });
這是一個非常簡單的 API 伺服器,使用 oak
,它會根據路由傳回恐龍資訊。讓我們啟動 API 伺服器
deno run --allow-env --allow-net api/main.ts
如果我們前往 localhost:8000
,我們會看到
到目前為止看起來不錯。
新增路由
我們的應用程式會有兩個路由:/
和 /:dinosaur
。
我們會使用 react-router-dom
作為我們的路由邏輯。讓我們將它新增到 vite.config.mjs
中的相依性
import { defineConfig } from "npm:vite@^3.1.3";
import react from "npm:@vitejs/plugin-react@^2.1";
import "npm:react@^18.2";
import "npm:react-dom@^18.2/client";
import "npm:react-router-dom@^6.4"; // Add this line
// https://vite.dev.org.tw/config/
export default defineConfig({
plugins: [react()],
});
一旦我們在那裡新增相依性,我們就可以在 React 應用程式中匯入它們,而不需要 npm:
規範。
接下來,讓我們前往 src/App.jsx
並新增我們的路由邏輯
import React from "react";
import {
BrowserRouter as Router,
Navigate,
Route,
Routes,
} from "react-router-dom";
import Index from "./pages/Index.jsx";
import Dinosaur from "./pages/Dinosaur.jsx";
export default function App(props) {
return (
<Router>
<Routes>
<Route exact path="/" element={<Index />} />
<Route exact path="/:dinosaur" element={<Dinosaur />} />
<Route path="*" element={<Navigate to="/" />} />
</Routes>
</Router>
);
}
接下來,讓我們新增 <Index>
和 <Dinosaur>
頁面。
新增頁面
這個應用程式中會有兩個頁面
src/pages/Index.jsx
:我們的索引頁面,它會列出所有恐龍src/pages/Dinosaur.jsx
:我們的恐龍頁面,它會顯示恐龍的詳細資料
我們會建立一個 src/pages
資料夾,並建立 .jsx
檔案
mkdir src/pages && touch src/pages/Index.jsx src/pages/Dinosaur.jsx
讓我們從 <Index>
開始。這個頁面會在 localhost:8000/api
中 fetch
,並透過 JSX 渲染它。
import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
const Index = () => {
const [dinos, setDinos] = useState([]);
useEffect(() => {
fetch(`https://127.0.0.1:8000/api/`)
.then(async (res) => await res.json())
.then((json) => setDinos(json));
}, []);
return (
<div>
<h1>Welcome to the Dinosaur app</h1>
<p>
Click on a dinosaur below to learn more.
</p>
<div>
{dinos.map((dino) => {
return (
<div>
<Link to={`/${dino.name.toLowerCase()}`}>{dino.name}</Link>
</div>
);
})}
</div>
</div>
);
};
export default Index;
接下來,在 <Dinosaur>
中,我們會做同樣的事情,但使用 localhost:8000/api/${dinosaur}
import React, { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
const Dinosaur = () => {
const { dinosaur } = useParams();
const [dino, setDino] = useState({});
useEffect(() => {
fetch(`https://127.0.0.1:8000/api/${dinosaur}`)
.then(async (res) => await res.json())
.then((json) => setDino(json));
}, []);
return (
<div>
<h1>{dino.name}</h1>
<p>
{dino.description}
</p>
<Link to="/">See all</Link>
</div>
);
};
export default Dinosaur;
讓我們啟動 React 應用程式
deno task start
並點選應用程式
歡呼!