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

相关文章

SpringShell命令行之交互式Shell应用开发方式

《SpringShell命令行之交互式Shell应用开发方式》本文将深入探讨SpringShell的核心特性、实现方式及应用场景,帮助开发者掌握这一强大工具,具有很好的参考价值,希望对大家有所帮助,如... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定

SpringBoot应用中出现的Full GC问题的场景与解决

《SpringBoot应用中出现的FullGC问题的场景与解决》这篇文章主要为大家详细介绍了SpringBoot应用中出现的FullGC问题的场景与解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录Full GC的原理与触发条件原理触发条件对Spring Boot应用的影响示例代码优化建议结论F

前端下载文件时如何后端返回的文件流一些常见方法

《前端下载文件时如何后端返回的文件流一些常见方法》:本文主要介绍前端下载文件时如何后端返回的文件流一些常见方法,包括使用Blob和URL.createObjectURL创建下载链接,以及处理带有C... 目录1. 使用 Blob 和 URL.createObjectURL 创建下载链接例子:使用 Blob

Vuex Actions多参数传递的解决方案

《VuexActions多参数传递的解决方案》在Vuex中,actions的设计默认只支持单个参数传递,这有时会限制我们的使用场景,下面我将详细介绍几种处理多参数传递的解决方案,从基础到高级,... 目录一、对象封装法(推荐)二、参数解构法三、柯里化函数法四、Payload 工厂函数五、TypeScript

MySQL 分区与分库分表策略应用小结

《MySQL分区与分库分表策略应用小结》在大数据量、复杂查询和高并发的应用场景下,单一数据库往往难以满足性能和扩展性的要求,本文将详细介绍这两种策略的基本概念、实现方法及优缺点,并通过实际案例展示如... 目录mysql 分区与分库分表策略1. 数据库水平拆分的背景2. MySQL 分区策略2.1 分区概念

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

C语言函数递归实际应用举例详解

《C语言函数递归实际应用举例详解》程序调用自身的编程技巧称为递归,递归做为一种算法在程序设计语言中广泛应用,:本文主要介绍C语言函数递归实际应用举例的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录前言一、递归的概念与思想二、递归的限制条件 三、递归的实际应用举例(一)求 n 的阶乘(二)顺序打印

Vue3使用router,params传参为空问题

《Vue3使用router,params传参为空问题》:本文主要介绍Vue3使用router,params传参为空问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐... 目录vue3使用China编程router,params传参为空1.使用query方式传参2.使用 Histo

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

CSS Padding 和 Margin 区别全解析

《CSSPadding和Margin区别全解析》CSS中的padding和margin是两个非常基础且重要的属性,它们用于控制元素周围的空白区域,本文将详细介绍padding和... 目录css Padding 和 Margin 全解析1. Padding: 内边距2. Margin: 外边距3. Padd