【三】从零搭建react-新 实现增删改查

1.router.js新增文章管理路由

<Route path="/app/*" element={<AppPage/>} >
    <Route path="home" element={<Home/>} />
    <Route path="article" element={<ArticleList/>} />
</Route>


api.js

const HISTORY = `/api`

const URL = {
    doUserLogin: `${HISTORY}/login/doSignIn`, //
    getBasicData: `${HISTORY}/index/getBasicData`,

    doArticleAdd: `${HISTORY}/index/doArticleAdd`,
    doArticleUpdate: `${HISTORY}/index/doArticleUpdate`,
    doArticleDelete: `${HISTORY}/index/doArticleDelete`,
    getArticleList: `${HISTORY}/index/getArticleList`,
}
export default URL


2.article.js

import React from 'react'
import { Table, Space,Button,Modal,Input, Form, Row, Col, Select, DatePicker, message,Pagination } from 'antd';

import moment from 'moment';
import 'moment/locale/zh-cn'
import {EditOutlined,DeleteOutlined } from '@ant-design/icons';

import RequestTools from 'utils/request.js'

moment.locale('zh-cn')
const { confirm } = Modal;
const { Option } = Select;
const dateFormat = 'YYYY-MM-DD';
const { TextArea } = Input;

const _req = new RequestTools()


class ArticleList extends React.Component {
    constructor(prors){
        super(prors)
        this.state={
            page:1, //显示页
            pagesize:5,//显示的条数
            count:0,// 总条数
            align:'center',
            data:[], //接收数据
            visible: false,
            upvisible: false,
            id:0,
            title:'',
            category:'',
            is_show:0,
            create_time:moment('', dateFormat) ,
            content:'',
            istrue:false //修改弹框

        }
    }
    componentDidMount() {
        this.getArticleList()
    }

    getArticleList = () => {
        const params = {}
        params.page = this.state.page;
        params.pagesize = this.state.pagesize;
        _req.axiosPost(params, 'getArticleList').then(res => {
            this.setState({
                data:res.data.data,
                count: res.data.count
            })
        })
    }

    // 错误提示
    error = (val) => {
        message.error(val);
    };
    // 成功提示
    success = (val) => {
        message.success(val);
    };
    // 弹框显示
    showArticleAdd = () => {
        this.setState({
            visible: true,
        });
    };
    hideArticleAdd = () => {
        this.setState({
            visible: false,
            upvisible: false,
            istrue:false
        });
    };

    // 点击确认
    handleOk = () => {


    };

    // 点击取消
    handleCancel = ()=> {
        this.setState({
            visible: false,
            upvisible: false,
            istrue:false
        });
    };


    // 添加
    onAddFinish = values => {
        let that = this;
        console.log('Received values of form: ', values);
        var params = {};
        params.title=values.title;
        params.category=values.category;
        params.is_show=values.is_show;
        params.create_time=values.create_time._d;
        params.content=values.content;
        console.log('Received params: ', params);

        _req.axiosPost(params, 'doArticleAdd').then(res => {
            console.log(res);

            if (res.code==0){
                that.success(res.data.msg)
                setTimeout(function (){
                    that.setState({
                        visible: false,
                        upvisible: false,
                    });
                    that.getArticleList()
                },800)
            }
        })
    }

    // 编辑
    update(text,record,index){
        console.log(text)
        console.log(record)
        console.log(index)
        new Promise((resolve)=>{
            this.setState({
                upvisible: true,
                id:record.id,
                title:record.title,
                category:record.category,
                is_show:record.is_show,
                create_time:moment(record.create_time,dateFormat),
                content:record.content
            });
            resolve()
        }).then(()=>{
            this.setState({
                istrue:true
            })
        })
    }

    // 获取编辑表单数据并发起请求
    onFinish = values => {
        let that = this
        const params = {};
        params.id= this.state.id;
        params.title=values.title;
        params.category=values.category;
        params.is_show=values.is_show;
        params.create_time=values.create_time._d;
        params.content=values.content;

        _req.axiosPost(params, 'doArticleUpdate').then(res => {
            if (res.code==0){
                that.success(res.data.msg)
                setTimeout(function (){
                    that.setState({
                        visible: false,
                        upvisible: false,
                    });
                    that.getArticleList()
                },800)
            }
        })


    }


    // 删除
    del(text,record,index){
        console.log(record.task_no)
        this.showDeleteConfirm(record.task_no)
    }
    // 删除弹框
    showDeleteConfirm(no) {
        let that = this;
        confirm({
            title: '是否确认删除?',
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            // 点击确认触发
            onOk() {
                _req.axiosPost({task_no:no}, 'doArticleDelete').then(res => {
                    if (res.code==0){
                        that.success(res.data.msg)
                        setTimeout(function (){
                            that.getArticleList()
                        },800)
                    }
                })
            },
            // 点击取消触发
            onCancel() {
                console.log('Cancel');
            },
        });
    }


    // 分页操作
    onChangePage = page => {
        new Promise((resolve, reject) => {
            this.setState({
                page: page, // 改变值
            });
            resolve()
        }).then(() => {
            this.getArticleList()
        })
    };


    render() {
        const { visible} = this.state;
        const columns = [
            {
                title: '标题',
                dataIndex: 'title',
                width: 150,
                align:this.state.align,
            },
            {
                title: '分类',
                dataIndex: 'category',
                width: 50,
                align:this.state.align,
            },
            {
                title: '显示',
                dataIndex: 'is_show',
                align:this.state.align,
                width: 20,
            },
            {
                title: '发布时间',
                dataIndex: 'create_time',
                align:this.state.align,
                width: 50,
            },
            {
                title: '操作',
                dataIndex: 'address',
                align:this.state.align,
                width: 150,
                render: (text, record,index) => (
                    <Space style={{
                        cursor: 'pointer',
                        color: '#2378f7',
                        fontSize: '15px'
                    }}>
                        <span onClick={()=>this.update(text,record,index)} ><EditOutlined /></span>
                        <span  onClick={()=>this.del(text,record,index)}> <DeleteOutlined /></span>
                    </Space>
                )
            }
        ];


        return (
            <div>
                <Row>
                    <Col span={2} offset={22}>
                        {/*添加弹框*/}
                        <Modal
                            visible={visible}
                            title="新增文章"
                            onCancel={this.hideArticleAdd}
                            footer={null}

                        >
                            <Form
                                style={{marginLeft:'-12px'}}
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 14 }}
                                layout="horizontal"
                                onFinish={this.onAddFinish}
                            >
                                <Form.Item name='title' label="标题">
                                    <Input  placeholder="标题"  />
                                </Form.Item>
                                <Form.Item name='category' label="分类">
                                    <Select>
                                        <Option value="新手任务" >新手任务</Option>
                                        <Option value="日常任务" >日常任务</Option>
                                        <Option value="活动任务" >活动任务</Option>
                                    </Select>
                                </Form.Item>
                                <Form.Item name='is_show' label="是否显示">
                                    <Select>
                                        <Option value="1" >显示</Option>
                                        <Option value="0" >隐藏</Option>
                                    </Select>
                                </Form.Item>
                                <Form.Item name='create_time' label="发布时间">
                                    <DatePicker />
                                </Form.Item>
                                <Form.Item name='content' label="内容">
                                    <TextArea
                                        placeholder="内容"
                                        autoSize={{ minRows: 3, maxRows: 5 }}
                                    />
                                </Form.Item>
                                <Form.Item style={{margin:'20px 0 0 120px '}} >
                                    <Button key="back" onClick={this.handleCancel}>
                                        取消
                                    </Button>,
                                    <Button key="submit" type="primary" htmlType="submit" >
                                        提交
                                    </Button>
                                </Form.Item>

                            </Form>
                        </Modal>
                        {/*修改弹框*/}
                        {this.state.istrue&& <Modal
                            visible={this.state.upvisible}
                            title="修改文章"
                            footer={null}
                            onCancel={this.handleCancel}
                        >
                            <Form
                                style={{marginLeft:'-12px'}}
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 14 }}
                                layout="horizontal"
                                onFinish={this.onFinish}
                                initialValues={{
                                    title:this.state.title,
                                    category:this.state.category,
                                    is_show:this.state.is_show,
                                    create_time:this.state.create_time,
                                    content:this.state.content,
                                }}
                            >
                                <Form.Item name='title' label="标题">
                                    <Input  placeholder="large size"  />
                                </Form.Item>
                                <Form.Item name='category' label="分类">
                                    <Select>
                                        <Option value="新手任务" >新手任务</Option>
                                        <Option value="日常任务" >日常任务</Option>
                                        <Option value="活动任务" >活动任务</Option>
                                    </Select>
                                </Form.Item>
                                <Form.Item name='is_show' label="是否显示">
                                    <Select>
                                        <Option value="1" >显示</Option>
                                        <Option value="0" >隐藏</Option>
                                    </Select>
                                </Form.Item>
                                <Form.Item name='create_time' label="发布日期">
                                    <DatePicker />
                                </Form.Item>
                                <Form.Item name='content' label="内容">
                                    <TextArea
                                        placeholder="内容"
                                        autoSize={{ minRows: 3, maxRows: 5 }}
                                    />
                                </Form.Item>
                                <Form.Item style={{margin:'20px 0 0 120px '}} >
                                    <Button key="back" onClick={this.handleCancel}>
                                        取消
                                    </Button>
                                    <Button key="submit" type="primary" htmlType="submit"  onClick={this.handleOk}>
                                        提交
                                    </Button>
                                </Form.Item>

                            </Form>
                        </Modal>}
                    </Col>
                </Row>
                <Row>
                    <Col span={24}>
                        <Button onClick={this.showArticleAdd} type="primary" style={{ marginBottom: 16 }}>
                            新增
                        </Button>
                        <Table pagination={false} columns={columns} dataSource={this.state.data}   />
                        <Pagination
                            current={this.state.page} // 总条数 绑定state中的值
                            onChange={this.onChangePage}  // 改变页面是发生的函数
                            pageSize={this.state.pagesize}
                            total={this.state.count}
                            // 页码数量 = 向上取整(总条数/每页条数)X10
                            showSizeChanger={false} // 总条数超过多少条显示也换条数
                            style={{ marginTop: '20px' }}
                        />

                    </Col>
                </Row>
            </div>
        )
    }
}

export default ArticleList


后台php

<?php
namespace app\api\controller;

use app\BaseController;

class Index extends BaseController
{
    public function getBasicData()
    {
        $arr = [
            'data'=>[
                'userCount'=>100,
                'productCount'=>120,
                'orderCount'=>140
            ],
            'code'=>0
        ];
        return $arr;
    }

    public function getArticleList()
    {
        $arr = [
            'data'=>[
                'data'=>[
                    ['id'=>1,'title'=>'test','create_time'=>'2022-01-31T13:53:27.237Z','category'=>'新手任务','is_show'=>1,'content'=>'4455666'],
                    ['id'=>2,'title'=>'test','create_time'=>'2022-01-31T13:53:27.237Z','category'=>'新手任务','is_show'=>0,'content'=>'4455666'],
                    ['id'=>3,'title'=>'test','create_time'=>'2022-01-31T13:53:27.237Z','category'=>'新手任务','is_show'=>1,'content'=>'4455666'],
                    ['id'=>4,'title'=>'test','create_time'=>'2022-01-31T13:53:27.237Z','category'=>'新手任务','is_show'=>0,'content'=>'4455666']
                ],
                'count'=>30
            ],
            'code'=>0
        ];
        return $arr;
    }

    public function doArticleUpdate()
    {
        $param = $this->request->param();
        file_put_contents('333345update.log',json_encode($param)."\r\n\r\n",FILE_APPEND);
        $arr = [
            'data'=>[
                'msg'=>'更新成功',
            ],
            'code'=>0
        ];
        return $arr;
    }

    public function doArticleAdd()
    {
        $param = $this->request->param();
        file_put_contents('333345add.log',json_encode($param)."\r\n\r\n",FILE_APPEND);
        $arr = [
            'data'=>[
                'msg'=>'新增成功',
            ],
            'code'=>0
        ];
        return $arr;
    }

    public function doArticleDelete()
    {
        $param = $this->request->param();
        file_put_contents('333345del.log',json_encode($param)."\r\n\r\n",FILE_APPEND);
        $arr = [
            'data'=>[
                'msg'=>'删除成功',
            ],
            'code'=>0
        ];
        return $arr;
    }

}


下一篇实现路由拦截和token的使用


# 正常构建
yarn build

# 构建到指定目录
BUILD_PATH=./dist yarn build

# 指定配置环境
REACT_APP_CONFIG_ENV=test yarn build

# 打包大小分析
yarn build:analyzer

# 打包时间分析
yarn build:time


打赏

看恩吧
网站不承担任何有关评论的责任
  • 最新评论
  • 总共条评论
取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦