首页 > 其他分享 >17.分类组件Category 动态获取数据

17.分类组件Category 动态获取数据

时间:2023-04-26 16:01:27浏览次数:37  
标签:Category loading const 17 分类 获取数据 state parentId setState

我们接下来做分类组件Category, 这个主要用来管理商品的分类,有一级和二级, 可以实现一级与二级之间跳转

/pages/category/category.jsx文件内容如下:

import React, {Component} from 'react'
import {Button, Card, Table, message} from 'antd'
import {
    PlusOutlined,
    DoubleRightOutlined
} from "@ant-design/icons";
import {reqCategories, reqAddCategory, reqUpdateCategory} from "../../api"
import LinkButton from '../../components/link-button'
/*
    商品分类路由
 */


export default class Category extends Component{
    state = {
        loading: false,
        categories: [],
        subCategories: [],
        parentId: '0',
        categoryName: '',
    }
    /*
        初始化Table所有列的数组
     */
    initColumns = () => {
        this.columns = [
            {
                title: '分类名称',
                dataIndex: 'name', // 显示数据对应的属性名信息
                // key: 'uniq_id',  // 可以增加 Table组件的 rowKey="uniq_id" 属性来替代
            },
            {
                title: '操作',
                width: 350,
                render: (categoryObj) => ( // 返回需要显示的表格界面操作标签
                    <span>
                        <LinkButton>修改分类</LinkButton>
                        {/* 如何向事件回调函数传递参数:先定义一个匿名函数,在函数调用处理的函数并传入参数*/}
                        {this.state.parentId === '0' ? <LinkButton onClick={() => this.showSubCategories(categoryObj)}>查看子分类</LinkButton> : null}
                    </span>
                )
            },
        ]
    }
    /*
        异步获取一级/二级分类数据
     */
    getCategories = async () => {
        // 发送请求前,显示loading
        this.setState({loading: true})
        const {parentId} = this.state
        // 发送异步ajax请求,获取分类数据,只有await才会获取的response,否则获取的是promise对象
        const result = await reqCategories(parentId)
        // 请求成功后,关闭loading
        this.setState({loading: false})
        if (result['code'] === 1) {
            const categories = result['data']
            // 更新state中一级分类的数据
            if(parentId === '0'){
                this.setState({categories})
            }else{
                // 更新state中二级分类的数据
                this.setState({subCategories: categories})
            }
        }else{
            message.error(result['message'])
        }
    }
    // 点击查看子分类,显示二级分类信息
    showSubCategories = (categoryObj) =>{
        // 更新状态, 有个问题就是setState是异步操作,导致无法正常获取parent_id,所以需要再增加一个回调函数
        this.setState({
            parentId: categoryObj.uniq_id,
            categoryName: categoryObj.name
        }, ()=>{ // 新增回调函数, 达到状态更新后且重新render后执行
            this.getCategories()
        })
    }
    // 点击一级分类列表 显示信息
    showCategories = () => {
        // 更新显示一级列表状态
        this.setState({
            subCategories: [],
            parentId: '0',
            categoryName: '',
        })
    }
    componentDidMount() {
        this.initColumns()
        this.getCategories()
    }
    render() {
        const {categories, subCategories, parentId, categoryName, loading} = this.state
        const title = this.state.parentId === '0' ? '一级分类列表' : (
            <span>
                <LinkButton onClick={this.showCategories}>一级分类列表</LinkButton>
                <DoubleRightOutlined style={{marginRight: 10}} />
                <span>{categoryName}</span>
            </span>
        )
        const extra = (
            <Button type="primary">
                <PlusOutlined />
                添加
            </Button>
        )
        return (
            <Card
                title={title}
                extra={extra}
            >
                <Table
                    bordered
                    rowKey="uniq_id"
                    loading={loading}
                    dataSource={parentId === '0' ? categories : subCategories}
                    columns={this.columns}
                    pagination={{
                        defaultPageSize: 5,
                        showQuickJumper: true,
                    }}
                />
            </Card>
        )
    }
}

整个项目已经开发完成,包括前后台,需要源码的可以联系: 微信号:guos_123

标签:Category,loading,const,17,分类,获取数据,state,parentId,setState
From: https://www.cnblogs.com/guo-s/p/17356319.html

相关文章

  • Qt+MySql开发笔记:Qt5.9.3的msvc2017x64版本编译MySql8.0.16版本驱动并Demo连接数据库
    前言  mysql驱动版本msvc2015x32版本调好,mysql的mingw32版本的驱动上一个版本编译并测试好,有些三方库最低支持vs2017,所以只能使用msvc2017x64,基于Qt5.9.3,于是本篇编译mysql驱动的msvc2017x64版本,满足当前的特定需求,这次过程有点费劲,可能是Qt的版本低于Qt5.12,继续无保留分享......
  • Python通过GPIO从DHT11温度传感器获取数据
    Python通过GPIO从DHT11温度传感器获取数据设备:树莓派4B、DHT11、杜邦线DHT11DHT11是一款有已校准数字信号输出的温湿度传感器。其精度湿度±5%RH,温度±2℃,量程湿度20-90%RH,温度0~50℃。精度不高,但价格低廉。DHT11使用单总线通信。供电电压3.3~5V。线路连接DHT11 树莓......
  • Oracle 19c的参数sec_case_sensitive_logon与ORA-01017错误
    Oracle的参数sec_case_sensitive_logon是Oracle11g开始被引入。这个参数主要是为了控制密码的大小写敏感问题。sec_case_sensitive_logon=true表示密码区分大小写。sec_case_sensitive_logon=false表示密码不区分大小写。从Oracle12c开始,参数sec_case_sensitive_logon被弃用......
  • Codeforces 1781G - Diverse Coloring(构造)
    vp时候想到大致思路了,但是死活调不对,赛后套取cf的数据调了好久才过/ll首先直觉告诉我们答案不会太大。稍微猜一猜可以猜出除了四个点的菊花之外答案都是\(n\bmod2\),下面我们来通过构造证明这件事情。首先,链的情况是trivial的,直接根据奇偶性间隔染色即可。如果不是链,那么......
  • 剑指 Offer II 017. 含有所有字符的最短字符串
    题目链接:剑指OfferII017.含有所有字符的最短字符串方法:同向双指针解题思路基本思路:统计\(t\)字符串中每个字符的个数,然后使用双指针遍历字符串\(s\),当窗口覆盖\(t\)中所有字符时,开始缩短左指针到可以到达的最右侧,取窗口最小的字符串为答案;需要考虑的问题:什么情况......
  • P.16-登录接口代码实现、P.17-测试接口
    P.16-登录接口代码实现自定义登陆接口,然后让SpringSecurity对这个接口放行,让用户访问这个接口的时候不用登录也能访问。在接口中我们通过AuthenticationManager的authenticate方法来进行用户认证,所以需要在SecurityConfig中配置把AuthenticationManager注入容器。......
  • COMP2017 C语方系统分析
    COMP20179017Assignment3Thisassignmentisworth5%+10%+30%ofyourfinalassessmentThisassessmentisCONFIDENTIAL.©UniversityofSydney.Due:•Milestone:23:59Wednesday26April2023localSydneytime.•Final:23:59Tuesday9May2023localSydn......
  • 2017 ACM-ICPC, Universidad Nacional de Colombia Programming Contest D
    AlexhastwomagicmachinesAandB.MachineAwillgiveyou2x + 1coinsifyouinsertxcoinsinit,machineBwillgiveyou2x + 2.Alexhasnocoinsandwantstogetexactlyncoinsinordertobuyanewunicorn,buthecan’tfigureouthowtodoi......
  • ECNA 2017 Problem J: Workout for a Dumbbell 模拟
    JimRatthasjustjoinedalocalfitnesscenter.He’sespeciallyexcitedaboutasequenceof10machinesthathecyclesthroughthreetimesforhisworkout.Hehasafixedtimewhichhespendsoneachmachine,aswellasafixedrecoverytimeafterusin......
  • 2017ACM/ICPC广西邀请赛-重现赛(感谢广西大学)C - Counting Stars 暴力三元环
    LittleAisanastronomylover,andhehasfoundthattheskywassobeautiful!Soheiscountingstarsnow!Therearenstarsinthesky,andlittleAhasconnectedthembymnon-directionaledges.Itisguranteedthatnoedgesconnectonestarwithi......