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

相关文章

MyBatis分页查询实战案例完整流程

《MyBatis分页查询实战案例完整流程》MyBatis是一个强大的Java持久层框架,支持自定义SQL和高级映射,本案例以员工工资信息管理为例,详细讲解如何在IDEA中使用MyBatis结合Page... 目录1. MyBATis框架简介2. 分页查询原理与应用场景2.1 分页查询的基本原理2.1.1 分

Vue和React受控组件的区别小结

《Vue和React受控组件的区别小结》本文主要介绍了Vue和React受控组件的区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录背景React 的实现vue3 的实现写法一:直接修改事件参数写法二:通过ref引用 DOMVu

使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解

《使用Python批量将.ncm格式的音频文件转换为.mp3格式的实战详解》本文详细介绍了如何使用Python通过ncmdump工具批量将.ncm音频转换为.mp3的步骤,包括安装、配置ffmpeg环... 目录1. 前言2. 安装 ncmdump3. 实现 .ncm 转 .mp34. 执行过程5. 执行结

Java实现将HTML文件与字符串转换为图片

《Java实现将HTML文件与字符串转换为图片》在Java开发中,我们经常会遇到将HTML内容转换为图片的需求,本文小编就来和大家详细讲讲如何使用FreeSpire.DocforJava库来实现这一功... 目录前言核心实现:html 转图片完整代码场景 1:转换本地 HTML 文件为图片场景 2:转换 H

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

PHP应用中处理限流和API节流的最佳实践

《PHP应用中处理限流和API节流的最佳实践》限流和API节流对于确保Web应用程序的可靠性、安全性和可扩展性至关重要,本文将详细介绍PHP应用中处理限流和API节流的最佳实践,下面就来和小编一起学习... 目录限流的重要性在 php 中实施限流的最佳实践使用集中式存储进行状态管理(如 Redis)采用滑动

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

SpringBoot 多环境开发实战(从配置、管理与控制)

《SpringBoot多环境开发实战(从配置、管理与控制)》本文详解SpringBoot多环境配置,涵盖单文件YAML、多文件模式、MavenProfile分组及激活策略,通过优先级控制灵活切换环境... 目录一、多环境开发基础(单文件 YAML 版)(一)配置原理与优势(二)实操示例二、多环境开发多文件版

Three.js构建一个 3D 商品展示空间完整实战项目

《Three.js构建一个3D商品展示空间完整实战项目》Three.js是一个强大的JavaScript库,专用于在Web浏览器中创建3D图形,:本文主要介绍Three.js构建一个3D商品展... 目录引言项目核心技术1. 项目架构与资源组织2. 多模型切换、交互热点绑定3. 移动端适配与帧率优化4. 可

深入浅出Spring中的@Autowired自动注入的工作原理及实践应用

《深入浅出Spring中的@Autowired自动注入的工作原理及实践应用》在Spring框架的学习旅程中,@Autowired无疑是一个高频出现却又让初学者头疼的注解,它看似简单,却蕴含着Sprin... 目录深入浅出Spring中的@Autowired:自动注入的奥秘什么是依赖注入?@Autowired