返回

用 React 和 Ant Design 实践小帮厨项目

前端

1. 项目介绍

作为一名初学者,我决定通过实战项目来检验自己的 React 学习成果,同时加深对 React 的理解。于是,我选择了一个小帮厨项目,旨在创建一个能够让用户轻松获取烹饪食谱、分享烹饪经验的平台。

2. 技术选型

为了实现项目目标,我选择了以下技术栈:

  • React:一个用于构建交互式 UI 的 JavaScript 库。
  • Ant Design:一个提供大量 UI 组件的 React 框架。
  • MongoDB:一个灵活、可扩展的文档型数据库。

3. 项目结构

项目结构如下:

├── client
│   ├── src
│   │   ├── App.js
│   │   ├── components
│   │   │   ├── RecipeCard.js
│   │   │   ├── RecipeForm.js
│   │   │   ├── RecipeList.js
│   │   │   └── UserForm.js
│   │   ├── pages
│   │   │   ├── Home.js
│   │   │   ├── Login.js
│   │   │   ├── Profile.js
│   │   │   └── Recipes.js
│   │   ├── services
│   │   │   ├── recipeService.js
│   │   │   └── userService.js
│   │   └── styles
│   │       └── App.css
│   ├── package.json
│   ├── index.html
├── server
│   ├── app.js
│   ├── config
│   │   ├── db.js
│   │   └── routes.js
│   ├── controllers
│   │   ├── recipeController.js
│   │   └── userController.js
│   ├── models
│   │   ├── Recipe.js
│   │   └── User.js
│   ├── package.json
│   ├── index.js
├── .gitignore
├── README.md
└── package.json

4. 路由设置

作为单页面应用,路由是必不可少的。在 config/routes.js 中,我设置了以下路由:

const routes = [
  { path: "/", component: Home },
  { path: "/login", component: Login },
  { path: "/profile", component: Profile },
  { path: "/recipes", component: Recipes },
];

export default routes;

5. UI 组件

为了实现更好的用户体验,我使用了 Ant Design 提供的 UI 组件。这些组件包括:

  • Button:用于执行操作的按钮。
  • Input:用于用户输入的文本框。
  • Form:用于收集用户输入数据的表单。
  • Table:用于展示数据的表格。
  • Modal:用于展示模态对话框。

6. RESTful API 设计

为了实现前后端分离,我设计了以下 RESTful API:

GET /recipes:获取所有食谱
GET /recipes/:id:获取指定 ID 的食谱
POST /recipes:创建新食谱
PUT /recipes/:id:更新指定 ID 的食谱
DELETE /recipes/:id:删除指定 ID 的食谱

7. MongoDB 集成

我使用 MongoDB 作为数据库,并在 server/config/db.js 中配置了数据库连接:

const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/recipe-app", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const db = mongoose.connection;

db.on("error", (err) => {
  console.error(err);
});

db.once("open", () => {
  console.log("Connected to MongoDB");
});

module.exports = db;

8. 项目部署

我使用以下命令来部署项目:

cd client
npm start

cd server
npm start

9. 项目展示

项目部署成功后,可以在浏览器中访问 http://localhost:3000 来查看项目效果。

10. 结语

通过这个项目,我不仅加深了对 React 的理解,也掌握了 React 和 Ant Design 的实际应用技巧。同时,我还学会了如何设计 RESTful API 和集成 MongoDB。我希望这个项目能够对其他 React 初学者有所帮助。