React+Redux+Ant Design+TypeScript 电子商务实战-客户端应用 03 分类、产品

本文主要是介绍React+Redux+Ant Design+TypeScript 电子商务实战-客户端应用 03 分类、产品,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

创建添加分类组件

创建组件文件

// src\components\admin\AddCategory.tsx
import { Button, Form, Input } from 'antd'
import { Link } from 'react-router-dom'
import Layout from '../core/Layout'const AddCategory = () => {const onFinish = (value: { name: string }) => {console.log(value)}return (<Layout title="添加分类" subTitle=""><Form onFinish={onFinish}><Form.Item name="name" label="分类名称"><Input /></Form.Item><Form.Item><Button type="primary" htmlType="submit">添加分类</Button></Form.Item></Form><Button><Link to="/admin/dashboard">返回 Dashboard</Link></Button></Layout>)
}export default AddCategory

配置路由

// src\Routes.tsx
import { HashRouter, Route, Switch } from 'react-router-dom'
import AddCategory from './components/admin/AddCategory'
import AdminDashboard from './components/admin/AdminDashboard'
import AdminRoute from './components/admin/AdminRoute'
import Dashboard from './components/admin/Dashboard'
import PrivateRoute from './components/admin/PrivateRoute'
import Home from './components/core/Home'
import Shop from './components/core/Shop'
import Signin from './components/core/Signin'
import Signup from './components/core/Signup'const Routes = () => {return (<HashRouter><Switch><Route path="/" component={Home} exact /><Route path="/shop" component={Shop} /><Route path="/signin" component={Signin} /><Route path="/signup" component={Signup} /><PrivateRoute path="/user/dashboard" component={Dashboard} /><AdminRoute path="/admin/dashboard" component={AdminDashboard} /><AdminRoute path="/create/category" component={AddCategory} /></Switch></HashRouter>)
}export default Routes

配置链接入口

// src\components\admin\AdminDashboard.tsx
import { Col, Descriptions, Menu, Row, Typography } from 'antd'
import { Link } from 'react-router-dom'
import Layout from '../core/Layout'
import { ShoppingCartOutlined, UserOutlined, OrderedListOutlined } from '@ant-design/icons'
import { Jwt } from '../../store/models/auth'
import { isAuth } from '../../helpers/auth'const { Title } = Typographyconst AdminDashboard = () => {const {user: { name, email }} = isAuth() as Jwtconst adminLinks = () => (<><Title level={5}>管理员链接</Title><Menu style={{ borderRight: 0 }}><Menu.Item><ShoppingCartOutlined style={{ marginRight: '5px' }} /><Link to="/create/category">添加分类</Link></Menu.Item><Menu.Item><UserOutlined style={{ marginRight: '5px' }} /><Link to="">添加产品</Link></Menu.Item><Menu.Item><OrderedListOutlined style={{ marginRight: '5px' }} /><Link to="">订单列表</Link></Menu.Item></Menu></>)const adminInfo = () => (<Descriptions title="管理员信息" bordered><Descriptions.Item label="昵称">{name}</Descriptions.Item><Descriptions.Item label="邮箱">{email}</Descriptions.Item><Descriptions.Item label="角色">管理员</Descriptions.Item></Descriptions>)return (<Layout title="管理员 dashboard" subTitle=""><Row><Col span="4">{adminLinks()}</Col><Col span="20">{adminInfo()}</Col></Row></Layout>)
}export default AdminDashboard

实现添加分类功能

// src\components\admin\AddCategory.tsx
import { Button, Form, Input, message } from 'antd'
import axios from 'axios'
import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { API } from '../../config'
import { isAuth } from '../../helpers/auth'
import { Jwt } from '../../store/models/auth'
import Layout from '../core/Layout'const AddCategory = () => {const [name, setName] = useState<string>('')const { user, token } = isAuth() as JwtuseEffect(() => {async function addCategory() {try {const response = await axios.post<{ name: string }>(`${API}/category/create/${user._id}`,{name: name},{headers: {Authorization: `Bearer ${token}`}})message.success(`[${response.data.name}] 分类添加成功`)} catch (error) {message.error(`${error.response.data.errors[0]}`)}}if (name) {addCategory()}}, [name])const onFinish = (value: { name: string }) => {setName(value.name)}return (<Layout title="添加分类" subTitle=""><Form onFinish={onFinish}><Form.Item name="name" label="分类名称"><Input /></Form.Item><Form.Item><Button type="primary" htmlType="submit">添加分类</Button></Form.Item></Form><Button><Link to="/admin/dashboard">返回 Dashboard</Link></Button></Layout>)
}export default AddCategory

创建添加产品组件

创建组件文件

// src\components\admin\AddProduct.tsx
import { Button, Form, Input, Select, Upload } from 'antd'
import Layout from '../core/Layout'const AddProduct = () => {return (<Layout title="添加产品" subTitle=""><Form><Form.Item label="上传封面"><Upload><Button>上传产品封面</Button></Upload></Form.Item><Form.Item name="name" label="产品名称"><Input /></Form.Item><Form.Item name="description" label="产品描述"><Input /></Form.Item><Form.Item name="price" label="产品价格"><Input /></Form.Item><Form.Item name="category" label="所属分类"><Select><Select.Option value="">请选择分类</Select.Option><Select.Option value="1">测试分类</Select.Option></Select></Form.Item><Form.Item name="quantity" label="产品库存"><Input /></Form.Item><Form.Item name="shipping" label="是否需要运输"><Select><Select.Option value={1}></Select.Option><Select.Option value={0}></Select.Option></Select></Form.Item><Form.Item><Button type="primary" htmlType="submit">添加产品</Button></Form.Item></Form></Layout>)
}export default AddProduct

配置路由

// src\Routes.tsx
import { HashRouter, Route, Switch } from 'react-router-dom'
import AddCategory from './components/admin/AddCategory'
import AddProduct from './components/admin/AddProduct'
import AdminDashboard from './components/admin/AdminDashboard'
import AdminRoute from './components/admin/AdminRoute'
import Dashboard from './components/admin/Dashboard'
import PrivateRoute from './components/admin/PrivateRoute'
import Home from './components/core/Home'
import Shop from './components/core/Shop'
import Signin from './components/core/Signin'
import Signup from './components/core/Signup'const Routes = () => {return (<HashRouter><Switch><Route path="/" component={Home} exact /><Route path="/shop" component={Shop} /><Route path="/signin" component={Signin} /><Route path="/signup" component={Signup} /><PrivateRoute path="/user/dashboard" component={Dashboard} /><AdminRoute path="/admin/dashboard" component={AdminDashboard} /><AdminRoute path="/create/category" component={AddCategory} /><AdminRoute path="/create/product" component={AddProduct} /></Switch></HashRouter>)
}export default Routes

配置链接入口

// src\components\admin\AdminDashboard.tsx
import { Col, Descriptions, Menu, Row, Typography } from 'antd'
import { Link } from 'react-router-dom'
import Layout from '../core/Layout'
import { ShoppingCartOutlined, UserOutlined, OrderedListOutlined } from '@ant-design/icons'
import { Jwt } from '../../store/models/auth'
import { isAuth } from '../../helpers/auth'const { Title } = Typographyconst AdminDashboard = () => {const {user: { name, email }} = isAuth() as Jwtconst adminLinks = () => (<><Title level={5}>管理员链接</Title><Menu style={{ borderRight: 0 }}><Menu.Item><ShoppingCartOutlined style={{ marginRight: '5px' }} /><Link to="/create/category">添加分类</Link></Menu.Item><Menu.Item><UserOutlined style={{ marginRight: '5px' }} /><Link to="/create/product">添加产品</Link></Menu.Item><Menu.Item><OrderedListOutlined style={{ marginRight: '5px' }} /><Link to="">订单列表</Link></Menu.Item></Menu></>)const adminInfo = () => (<Descriptions title="管理员信息" bordered><Descriptions.Item label="昵称">{name}</Descriptions.Item><Descriptions.Item label="邮箱">{email}</Descriptions.Item><Descriptions.Item label="角色">管理员</Descriptions.Item></Descriptions>)return (<Layout title="管理员 dashboard" subTitle=""><Row><Col span="4">{adminLinks()}</Col><Col span="20">{adminInfo()}</Col></Row></Layout>)
}export default AdminDashboard

获取分类列表

创建分类相关的 action

// src\store\models\category.ts
export interface Category {_id: stringname: string
}
// src\store\actions\category.action.ts
import { Category } from '../models/category'export const GET_CATEGORY = 'GET_CATEGORY'
export const GET_CATEGORY_SUCCESS = 'GET_CATEGORY_SUCCESS'export interface GetCategoryAction {type: typeof GET_CATEGORY
}export interface GetCategorySuccessAction {type: typeof GET_CATEGORY_SUCCESSpayload: Category[]
}export const getCategory = (): GetCategoryAction => ({type: GET_CATEGORY
})export const getCategorySuccess = (payload: Category[]): GetCategorySuccessAction => ({type: GET_CATEGORY_SUCCESS,payload
})// action 的联合类型
export type CategoryUnionType = GetCategoryAction | GetCategorySuccessAction

定义 reducer

// src\store\reducers\category.reducer.ts
import { CategoryUnionType, GET_CATEGORY, GET_CATEGORY_SUCCESS } from '../actions/category.action'
import { Category } from '../models/category'export interface CategoryState {category: {loaded: booleansuccess: booleanresult: Category[]}
}const initialState: CategoryState = {category: {loaded: false,success: false,result: []}
}export default function categoryReducer(state = initialState, action: CategoryUnionType) {switch (action.type) {case GET_CATEGORY:return {...state,category: {loaded: false,success: false,result: []}}case GET_CATEGORY_SUCCESS:return {...state,category: {loaded: true,success: true,result: action.payload}}default:return state}
}
// src\store\reducers\index.ts
import { connectRouter, RouterState } from 'connected-react-router'
import { History } from 'history'
import { combineReducers } from 'redux'
import authReducer, { AuthState } from './auth.reducer'
import categoryReducer, { CategoryState } from './category.reducer'
// import testReducer from './test.reducer'// 定义一个包含 router 的 store 类型接口 供外部使用
export interface AppState {router: RouterStateauth: AuthStatecategory: CategoryState
}const createRootReducer = (history: History) =>combineReducers({// test: testReducer,router: connectRouter(history),auth: authReducer,category: categoryReducer})export default createRootReducer

定义 sage

// src\store\sagas\category.sage.ts
import axios, { AxiosResponse } from 'axios'
import { put, takeEvery } from 'redux-saga/effects'
import { API } from '../../config'
import { getCategorySuccess, GET_CATEGORY } from '../actions/category.action'
import { Category } from '../models/category'function* handleGetCategory() {const response: AxiosResponse = yield axios.get<Category[]>(`${API}/categories`)yield put(getCategorySuccess(response.data))
}export default function* categorySage() {// 获取分类列表yield takeEvery(GET_CATEGORY, handleGetCategory)
}
// src\store\sagas\index.ts
import { all } from 'redux-saga/effects'
import authSaga from './auth.saga'
import categorySage from './category.sage'export default function* rootSaga() {yield all([authSaga(), categorySage()])
}

修改组件

// src\components\admin\AddProduct.tsx
import { Button, Form, Input, Select, Upload } from 'antd'
import Layout from '../core/Layout'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getCategory } from '../../store/actions/category.action'
import { AppState } from '../../store/reducers'
import { CategoryState } from '../../store/reducers/category.reducer'const AddProduct = () => {const dispatch = useDispatch()const category = useSelector<AppState, CategoryState>(state => state.category)useEffect(() => {dispatch(getCategory())}, [])return (<Layout title="添加产品" subTitle=""><ForminitialValues={{category: '',shipping: 0}}><Form.Item><Upload label="上传封面"><Button>上传产品封面</Button></Upload></Form.Item><Form.Item name="name" label="产品名称"><Input /></Form.Item><Form.Item name="description" label="产品描述"><Input /></Form.Item><Form.Item name="price" label="产品价格"><Input /></Form.Item><Form.Item name="category" label="所属分类"><Select><Select.Option value="">请选择分类</Select.Option>{category.category.result.map(item => (<Select.Option key={item._id} value={item._id}>{item.name}</Select.Option>))}</Select></Form.Item><Form.Item name="quantity" label="产品库存"><Input /></Form.Item><Form.Item name="shipping" label="是否需要运输"><Select><Select.Option value={1}></Select.Option><Select.Option value={0}></Select.Option></Select></Form.Item><Form.Item><Button type="primary" htmlType="submit">添加产品</Button></Form.Item></Form></Layout>)
}export default AddProduct

实现添加产品功能

// src\components\admin\AddProduct.tsx
import { Button, Form, Input, message, Select, Upload } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import Layout from '../core/Layout'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getCategory } from '../../store/actions/category.action'
import { AppState } from '../../store/reducers'
import { CategoryState } from '../../store/reducers/category.reducer'
import { RcFile, UploadProps } from 'antd/lib/upload'
import axios from 'axios'
import { API } from '../../config'
import { isAuth } from '../../helpers/auth'
import { Jwt } from '../../store/models/auth'// 将图片转化为 Data Url
function getBase64(blob: RcFile, callback: (e: string) => void) {const reader = new FileReader()reader.addEventListener('load', () => callback(reader.result as string))reader.readAsDataURL(blob)
}const AddProduct = () => {const dispatch = useDispatch()const [file, setFile] = useState<RcFile>()const category = useSelector<AppState, CategoryState>(state => state.category)useEffect(() => {dispatch(getCategory())}, [])// 产品封面 Data Urlconst [imgUrl, setImgUrl] = useState<string>()// 上传产品封面按钮const uploadButton = (<div><PlusOutlined /><div style={{ marginTop: 8 }}>Upload</div></div>)// Upload 组件属性const props: UploadProps = {accept: 'image/*',showUploadList: false,listType: 'picture-card',beforeUpload(file: RcFile) {// 获取文件保存下来等待和表单一起提交setFile(file)// 阻止默认上传行为(发送请求)return false},onChange({ file }) {// 获取图片的 Data Url 显示在页面getBase64(file as RcFile, (dataUrl: string) => {setImgUrl(dataUrl)})}}const addProductForm = () => {const { user, token } = isAuth() as Jwtconst onFinish = (product: any) => {// 要将二进制图片和普通文本字段结合在一起发送需要用到 FormDataconst formData = new FormData()for (let attr in product) {formData.set(attr, product[attr])}if (typeof file !== 'undefined') {formData.set('photo', file)}axios.post(`${API}/product/create/${user._id}`, formData, {headers: {Authorization: `Bearer ${token}`}}).then(() => {message.success('产品添加成功')}).catch(() => {message.success('产品添加失败')})}return (<FormonFinish={onFinish}initialValues={{category: '',shipping: 0}}><Form.Item label="上传封面"><Upload {...props}>{imgUrl ? (<img src={imgUrl} alt="产品封面" style={{ maxWidth: '100%', maxHeight: '100%' }} />) : (uploadButton)}</Upload></Form.Item><Form.Item name="name" label="产品名称"><Input /></Form.Item><Form.Item name="description" label="产品描述"><Input /></Form.Item><Form.Item name="price" label="产品价格"><Input /></Form.Item><Form.Item name="category" label="所属分类"><Select><Select.Option value="">请选择分类</Select.Option>{category.category.result.map(item => (<Select.Option key={item._id} value={item._id}>{item.name}</Select.Option>))}</Select></Form.Item><Form.Item name="quantity" label="产品库存"><Input /></Form.Item><Form.Item name="shipping" label="是否需要运输"><Select><Select.Option value={1}></Select.Option><Select.Option value={0}></Select.Option></Select></Form.Item><Form.Item><Button type="primary" htmlType="submit">添加产品</Button></Form.Item></Form>)}return (<Layout title="添加产品" subTitle="">{addProductForm()}</Layout>)
}export default AddProduct

这篇关于React+Redux+Ant Design+TypeScript 电子商务实战-客户端应用 03 分类、产品的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1097936

相关文章

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

在Spring Boot中集成RabbitMQ的实战记录

《在SpringBoot中集成RabbitMQ的实战记录》本文介绍SpringBoot集成RabbitMQ的步骤,涵盖配置连接、消息发送与接收,并对比两种定义Exchange与队列的方式:手动声明(... 目录前言准备工作1. 安装 RabbitMQ2. 消息发送者(Producer)配置1. 创建 Spr

深度解析Spring Boot拦截器Interceptor与过滤器Filter的区别与实战指南

《深度解析SpringBoot拦截器Interceptor与过滤器Filter的区别与实战指南》本文深度解析SpringBoot中拦截器与过滤器的区别,涵盖执行顺序、依赖关系、异常处理等核心差异,并... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实

MySQL中的索引结构和分类实战案例详解

《MySQL中的索引结构和分类实战案例详解》本文详解MySQL索引结构与分类,涵盖B树、B+树、哈希及全文索引,分析其原理与优劣势,并结合实战案例探讨创建、管理及优化技巧,助力提升查询性能,感兴趣的朋... 目录一、索引概述1.1 索引的定义与作用1.2 索引的基本原理二、索引结构详解2.1 B树索引2.2

前端如何通过nginx访问本地端口

《前端如何通过nginx访问本地端口》:本文主要介绍前端如何通过nginx访问本地端口的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、nginx安装1、下载(1)下载地址(2)系统选择(3)版本选择2、安装部署(1)解压(2)配置文件修改(3)启动(4)

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(

Java Web实现类似Excel表格锁定功能实战教程

《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.

HTML中meta标签的常见使用案例(示例详解)

《HTML中meta标签的常见使用案例(示例详解)》HTMLmeta标签用于提供文档元数据,涵盖字符编码、SEO优化、社交媒体集成、移动设备适配、浏览器控制及安全隐私设置,优化页面显示与搜索引擎索引... 目录html中meta标签的常见使用案例一、基础功能二、搜索引擎优化(seo)三、社交媒体集成四、移动

HTML input 标签示例详解

《HTMLinput标签示例详解》input标签主要用于接收用户的输入,随type属性值的不同,变换其具体功能,本文通过实例图文并茂的形式给大家介绍HTMLinput标签,感兴趣的朋友一... 目录通用属性输入框单行文本输入框 text密码输入框 password数字输入框 number电子邮件输入编程框