【七】从零搭建react-新 优化缓存和条件查询

1.util下新建 storage.js

//工具类

const get = (key) => {
    var overTime = localStorage.getItem('over_time');
    var time = Date.now();
    if(overTime > time){
        localStorage.setItem('over_time',time+3600000)
        return localStorage.getItem(key)
    }else{
        localStorage.setItem('isLogin',false)
        localStorage.setItem('over_time',1)
        localStorage.setItem('username',null)
        localStorage.setItem('token',null)
        window.location.href = "#/"
    }
}

const set = (key, value) => {
    localStorage.setItem(key, value)
}

const storage = {
    set,
    get,
};

export default storage

2. server.js  token 修改为通过storage获取

image.png


3.优化文章列表和新增修改

article.js

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

import moment from 'moment'
import 'moment/locale/zh-cn'
import './article.less'

import NavDom from 'components/NavDom/NavDom'
import RequestTools from 'utils/request'
import storage from "utils/storage";
import {Link} from "react-router-dom";

moment.locale('zh-cn')
const { confirm } = Modal
const { Option } = Select
const { RangePicker } = DatePicker;

const _req = new RequestTools()

class ArticleList extends Component {
    constructor(prors){
        super(prors)
        this.state={
            page:1, //显示页
            pagesize:10,//显示的条数
            count:0,// 总条数
            align:'center',
            data:[], //接收数据
            keywords:'',
            category:'',
            status:'',
            update_time:'',
            options:[],
            selectedRowKeys:[]

        }

        this.rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.state.selectedRowKeys = selectedRowKeys
                console.log(this.state)
            },
        };

        this.formRef = {};

        _req.axiosPostSync({}, 'getCategoryList').then(res => {
            console.log('getCategoryList',res.data)
            this.state.options = res.data
            storage.set('category', JSON.stringify(res.data))
        })

        _req.axiosPostSync({}, 'getTagsList').then(res => {
            storage.set('tags', JSON.stringify(res.data))
        })
    }

    componentDidMount() {
        // this.state.options = JSON.parse(storage.get('category'))
        this.getArticleList()
    }

    getArticleList = () => {
        const params = {}
        params.page = this.state.page;
        params.pagesize = this.state.pagesize;
        console.log(this.state)
        console.log(this.state.keywords)
        this.state.keywords && (params.keywords = this.state.keywords);
        this.state.category && (params.category = this.state.category);
        this.state.status && (params.status = this.state.status);
        this.state.update_time && (params.update_time = this.state.update_time);
        console.log('查询参数',params)
        _req.axiosPost(params, 'getArticleList').then(res => {
            this.setState({
                data:res.data.data,
                count: res.data.statistic.count
            })
        })
    }

    // 错误提示
    error = (val) => {
        message.error(val);
    };
    // 成功提示
    success = (val) => {
        message.success(val);
    };

    searchInputChange = (e) =>{
        console.log(e)
        this.state[e.target.id] = e.target.value
    }

    searchCascaderChange = (e) =>{
        this.state.category = JSON.stringify(e)
    }

    searchStatusChange = (e) =>{
        this.state.status = e
    }

    searchTimeChange = (e) =>{
        console.log(e)
        this.state.update_time = JSON.stringify([moment(e[0]).unix(),moment(e[1]).unix()])
        console.log(this.state)
    }

    // 添加
    toSearch = (e)  => {
        console.log('tosearch')
        this.getArticleList()
    }

    toReset = (e) => {
        var that = this;
        this.setState({
            keywords : '',
            category : '',
            status : '',
            update_time : ''
        },(e) => {
            that.formRef.resetFields();
            that.getArticleList()
        })
        console.log(this.state)
    }

    publish(text,record,index){
        let that = this;
        console.log(record)

        confirm({
            title: '确定发布此条资讯?',
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            // 点击确认触发
            onOk() {
                _req.axiosPost({id:record.id,is_public:1}, 'doArticlePublic').then(res => {
                    if (res.code===0){
                        that.success(res.data.msg)
                        setTimeout(function (){
                            that.getArticleList()
                        },800)
                    }
                })
            },
            // 点击取消触发
            onCancel() {
                console.log('Cancel');
            },
        });
    }

    unpublish(text,record,index){
        let that = this;
        console.log(record)

        confirm({
            title: '确定取消发布此条资讯?',
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            // 点击确认触发
            onOk() {
                _req.axiosPost({id:record.id,is_public:0}, 'doArticlePublic').then(res => {
                    if (res.code===0){
                        that.success(res.data.msg)
                        setTimeout(function (){
                            that.getArticleList()
                        },800)
                    }
                })
            },
            // 点击取消触发
            onCancel() {
                console.log('Cancel');
            },
        });
    }

    // 删除
    del(text,record,index){
        let that = this;
        console.log(record)

        confirm({
            title: '确定删除本条资讯信息吗?',
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            // 点击确认触发
            onOk() {
                _req.axiosPost({id:record.id}, 'doArticleDelete').then(res => {
                    if (res.code===0){
                        that.success(res.data.msg)
                        setTimeout(function (){
                            that.getArticleList()
                        },800)
                    }
                })
            },
            // 点击取消触发
            onCancel() {
                console.log('Cancel');
            },
        });
    }


    batchDel = () => {
        let that = this;
        let selected = that.state.selectedRowKeys
        if(selected.length <=0){
            that.error('至少选择一条资讯')
            return false;
        }
        let ids = JSON.stringify(selected)
        confirm({
            title: '确定下架并删除所有选中资讯信息吗?',
            okText: '确认',
            okType: 'danger',
            cancelText: '取消',
            // 点击确认触发
            onOk() {
                _req.axiosPost({bathData:ids}, 'doArticleBatchDel').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 columns = [
            {
                title: '封面',
                dataIndex: 'thumb',
                width: 150,
                align:this.state.align,
                render:(text,record,index) =>{
                    if(text !== ''){
                        return (
                            <img src={text} style={{width:100}} alt=""/>
                        )
                    }
                }
            },
            {
                title: '标题',
                dataIndex: 'title',
                width: 150,
                align:this.state.align,
            },
            {
                title: '分类',
                dataIndex: 'category_name',
                width: 80,
                align:this.state.align,
            },
            {
                title: '状态',
                dataIndex: 'public',
                align:this.state.align,
                width: 20,
                render:(text, record,index) =>{
                    if(record.is_public){
                        return (
                            <span>已发布</span>
                        )
                    }else{
                        return (
                            <span style={{color:'red'}}>未发布</span>
                        )
                    }
                }
            },
            {
                title: '阅读量',
                dataIndex: 'viewnum',
                align:this.state.align,
                width: 20,
            },
            {
                title: '更新时间',
                dataIndex: 'update_time',
                align:this.state.align,
                width: 50,
            },
            {
                title: '操作',
                dataIndex: 'act',
                align:this.state.align,
                width: 150,
                render: (text, record,index) => {
                    if (record.is_public) {
                        return (
                            <Space style={{
                                cursor: 'pointer',
                                color: '#2378f7',
                                fontSize: '15px'
                            }}>
                                <span onClick={() => this.unpublish(text, record, index)}>下架</span>
                                <span><Link to={"/app/articleEdit"} state={{record}}>编辑</Link></span>
                                <span onClick={() => this.del(text, record, index)}>删除</span>
                            </Space>
                        )
                    }else{
                        return (
                            <Space style={{
                                cursor: 'pointer',
                                color: '#2378f7',
                                fontSize: '15px'
                            }}>
                                <span onClick={() => this.publish(text, record, index)}>发布</span>
                                <span><Link to={"/app/articleEdit"} state={{record}}>编辑</Link></span>
                                <span onClick={() => this.del(text, record, index)}>删除</span>
                            </Space>
                        )
                    }
                }
            }
        ];



        return (
            <div className='article_content_div'>
                <Row className="list_crumbs">
                    <NavDom breads={[{'title':'资讯管理', 'url':'/app/article'},{'title':'资讯列表', 'url':''}]}/>
                </Row>
                <Row className="list_searchBar">
                    <Form
                        autoComplete="off"
                        ref={(r)=>{this.formRef = r}}
                    >
                        <Form.Item
                            label="标题"
                            name="keywords"
                        >
                            <Input onChange={(e) => this.searchInputChange(e)} placeholder={`输入关键字查询`}/>
                        </Form.Item>
                        <Form.Item
                            label="分类"
                            name="category"
                        >
                            <Cascader options={this.state.options} onChange={(e) => this.searchCascaderChange(e)} placeholder="分类" allowClear />
                        </Form.Item>
                        <Form.Item
                            label="状态"
                            name="status"
                        >
                            <Select onChange={(e) => this.searchStatusChange(e)} placeholder="是否发布" allowClear>
                                <Option value="1">已发布</Option>
                                <Option value="0">未发布</Option>
                            </Select>
                        </Form.Item>
                        <Form.Item
                            label="更新时间"
                            name="update_time"
                        >
                            <RangePicker onChange={(e) => this.searchTimeChange(e)} placeholder={['起始时间','结束时间']} allowClear />
                        </Form.Item>
                        <Form.Item  wrapperCol={{ span: 24 }}>
                            <Button type="primary" onClick={this.toSearch}>
                                查询
                            </Button>
                            <Button htmlType="button" onClick={this.toReset}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form>
                </Row>
                <Row className="list_content">
                    <Col span={24}>
                        <div className="list_content_btndiv">
                            <Button type="primary" >
                                <Link to="/app/articleAdd">新增</Link>
                            </Button>
                            <Button onClick={this.batchDel} htmlType="button" >
                                批量删除
                            </Button>
                        </div>
                        <Table rowSelection={this.rowSelection} pagination={false} columns={columns} dataSource={this.state.data} rowKey={columns => columns.id}    />
                        <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


article.less

.article_content_div .ant-form-item{
  min-width: 150px;
  margin-left: 15px;
}


articleAdd.js

import React,{ useState } from 'react'
import {Button, Input, Form, Row, Col, Select, message, Cascader, Radio, Space, Upload} from 'antd';
import ImgCrop from 'antd-img-crop';
import { UploadOutlined } from '@ant-design/icons';

import moment from 'moment';
import 'moment/locale/zh-cn'

import UEditor from 'components/Editor/Editor';
import NavDom from 'components/NavDom/NavDom';
import url from 'api/api';
import storage from 'utils/storage'
import RequestTools from 'utils/request'
import { useNavigate } from "react-router-dom";
import './articleAdd.less'

moment.locale('zh-cn')
const { Option } = Select;
const { TextArea } = Input;

const _req = new RequestTools()


function ArticleAdd() {
    let navigate = useNavigate();

    const [editorContent, setEditorContent] = useState('');
    const [cover_image, setCover_image] = useState('');
    const [attach, setAttach] = useState('');
    const [type, setType] = useState(1);
    const [status, setStatus] = useState(0);
    const [fileList, setFileList] = useState([]);
    const [visible_type, setVisible_type] = useState('block');
    const [visible_type_2, setVisible_type_2] = useState('none');

    const options = JSON.parse(storage.get('category'))
    const tags = JSON.parse(storage.get('tags'))
    const children = [];
    for (let i in tags) {
        children.push(<Option key={i} value={i}>{tags[i]}</Option>);
    }
    console.log('children',children)

    const props = {
        name: 'file',
        action: url['doUploadAttach'],
        headers: {
            authorization: 'authorization-text',
        },
        data:{
            token:storage.get('token')
        },
        onChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                console.log(info.file)
                setAttach(info.file.response.data.file)
                message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
    };

    // 错误提示
    const error = (val) => {
        message.error(val);
    };
    // 成功提示
    const success = (val) => {
        message.success(val);
    };

    const onEditorChange = (editorContent) => {
        setEditorContent(editorContent)
    };

    const onChangeType = (e) => {
        console.log('onChangeType',e)
        setType(e.target.value)
        if(e.target.value === '1' || e.target.value === 1){
            setVisible_type('block')
            setVisible_type_2('none')
        }else{
            setVisible_type('none')
            setVisible_type_2('block')
        }
    }

    const onChangeTags = (e) => {
        console.log(e);
    }

    const onFileChange = ({ file,event,fileList: newFileList }) => {
        console.log('上传返回的信息')
        console.log(file)
        console.log(file.status)
        if(file.status === 'done' && file.response.code === 0){
            console.log(file.response.code)
            console.log(file.response.data.file)
            setCover_image(file.response.data.file)
        }
        setFileList(newFileList);

    };

    const onPreview = async file => {
        let src = file.url;
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj);
                reader.onload = () => resolve(reader.result);
            });
        }
        const image = new Image();
        image.src = src;
        const imgWindow = window.open(src);
        imgWindow.document.write(image.outerHTML);
    };


    const onSubmit = (e) =>{
        console.log(1122)
        setStatus(1)
    }

    const onSubmitTest = (e) =>{
        console.log(112212)

        setStatus(0)
    }

    // 添加
    const onAddFinish = values => {

        console.log('Received values of form: ', values);
        var params = {};
        params.title=values.title;
        params.category=JSON.stringify(values.category);
        params.author=values.author;
        params.tags=JSON.stringify(values.tags);
        params.tags_2=values.tags_2;
        params.description=values.description;

        params.type=type;
        params.content=editorContent?editorContent:'';
        params.source_url=values.source_url?values.source_url:'';
        params.thumb=cover_image;
        params.attach=attach;
        params.status=status;

        console.log('Received params: ', params);

        if(params.type === '1' || params.type === 1){
            if(editorContent === ''){
                error('正文不能为空');
                return false;
            }
        }else{
            if(params.source_url === ''){
                error('原文链接不能为空');
                return false;
            }
        }

        if(cover_image === ''){
            error('封面图必须上传');
            return false;
        }
        _req.axiosPost(params, 'doArticleAdd').then(res => {
            console.log(res);

            if (res.code===0){
                success(res.data.msg)
                setTimeout(function (){
                    navigate('/app/article',{replace: true})
                },800)
            }else{
                error(res.desc)
            }
        })
    }

    return (
        <div>
            <Row className="list_crumbs">
                <NavDom breads={[{'title':'资讯管理', 'url':'/app/article'},{'title':'资讯新增', 'url':''}]}/>
            </Row>
            <Row className="list_content">
                <Col span={24}>
                    <Form
                        style={{marginLeft:'-12px'}}
                        labelCol={{ span: 2 }}
                        wrapperCol={{ span: 18 }}
                        layout="horizontal"
                        autoComplete="off"
                        onFinish={onAddFinish}
                    >
                        <Form.Item
                            name='title'
                            label="标题"
                            rules={[{required:true,message:'标题必填'}]}
                        >
                            <Input  placeholder="标题"  />
                        </Form.Item>
                        <Form.Item label="分类">
                            <Form.Item
                                name='category'
                                className='article_add_select_category'
                                rules={[{required:true,message:'分类必选'}]}
                            >
                                <Cascader options={options} placeholder="分类" allowClear />
                            </Form.Item>
                            <Form.Item
                                name='author'
                                label="作者"
                                className='article_add_input_author'
                            >
                                <Input placeholder="作者"  />
                            </Form.Item>
                        </Form.Item>
                        <Form.Item
                            label="类型"
                            rules={[{required:true}]}
                        >
                            <Radio.Group name='type' onChange={onChangeType} value={type}>
                                <Radio value={1}>原创</Radio>
                                <Radio value={0}>转载</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label="标签">
                            <Form.Item
                                name='tags'
                                className='article_add_select_tags'
                                rules={[{required:true,message:'标签必选'}]}
                            >
                                <Select
                                    mode="multiple"
                                    allowClear
                                    placeholder="标签"
                                    onChange={onChangeTags}
                                >
                                    {children}
                                </Select>
                            </Form.Item>
                            <Form.Item
                                name='tags_2'
                                className='article_add_input_tags'
                            >
                                <Input placeholder="自定义标签,使用逗号分割"  />
                            </Form.Item>
                        </Form.Item>
                        <div style={{display:visible_type}}>
                            <Form.Item
                                label="正文"
                            >
                                <UEditor content={editorContent} onChange={onEditorChange} width="600px" height="700px" />
                            </Form.Item>
                        </div>
                        <div style={{display:visible_type_2}}>
                            <Form.Item
                                name='source_url'
                                label="原文链接"
                            >
                                <Input  placeholder="原文链接"  />
                            </Form.Item>
                        </div>

                        <Form.Item
                            label="上传封面图"
                        >
                            <Form.Item
                                name='cover_image'
                                className='article_add_upload_cover'
                            >
                                <ImgCrop rotate>
                                    <Upload
                                        accept="image/*"
                                        action={url['doUploadImg']}
                                        data={{token : storage.get('token')}}
                                        listType="picture-card"
                                        fileList={fileList}
                                        onChange={onFileChange}
                                        onPreview={onPreview}
                                    >
                                        {fileList.length < 1 && '封面图'}
                                    </Upload>
                                </ImgCrop>
                            </Form.Item>
                            <Form.Item
                                name='description'
                                label="摘要"
                                className='article_add_input_description'
                                rules={[{required:true,message:'摘要必填'}]}
                            >
                                <TextArea
                                    rows={4}
                                    placeholder="摘要"
                                    style={{height:104}}
                                />
                            </Form.Item>
                            <Space>提示:建议尺寸640*360像素或比例16:9,格式:jpg、png,小于5M的图片</Space>
                        </Form.Item>

                        <Form.Item  label="附件">
                            <Upload {...props}>
                                <Button icon={<UploadOutlined />}>上传附件</Button>
                            </Upload>
                            <Space>提示:建议格式为word、excel、ppt、pdf,小于10M以内</Space>
                        </Form.Item>

                        <Form.Item className='submitBtn' style={{margin:'20px 0 0 120px '}} >
                            <Button key="submit" type="primary" htmlType="submit" onClick={onSubmit} >
                                提交
                            </Button>
                            <Button >
                                预览
                            </Button>
                            <Button htmlType="submit" onClick={onSubmitTest}>
                                保存草稿
                            </Button>
                        </Form.Item>
                    </Form>
                </Col>
            </Row>
        </div>
    )
}

export default ArticleAdd


articleAdd.less

//.article_add_select_category{
//  float: left;
//}

.article_add_select_category,.article_add_input_author{
  display:inline-flex;
  //width:300px;
  margin-bottom: 0;
}
.article_add_select_category,.article_add_select_tags{
  margin-left: 0;
}

.article_add_select_tags,.article_add_input_tags{
  display:inline-flex;
  width:45%;
  margin-bottom: 0;
}

#edui1,#edui1_iframeholder{
  width: 100% !important;
}

.article_add_input_description,.article_add_upload_cover{
  display: inline-flex;
  margin-bottom: 0;
}
.article_add_upload_cover{
  margin-left: 0;
}
.article_add_upload_cover .ant-upload-select-picture-card,.article_add_upload_cover .ant-upload-list-picture-card-container{
  margin-bottom: 0;
}

.ant-space{
  margin-top: 8px;
}

.article_add_input_description{
  width: 60%;
}
.submitBtn .ant-btn{
  margin-left: 15px;
}

articleEdit.js

import React,{ useState } from 'react'
import {Button, Input, Form, Row, Col, Select, message, Cascader, Radio, Space, Upload} from 'antd';
import ImgCrop from 'antd-img-crop';
import { UploadOutlined } from '@ant-design/icons';

import moment from 'moment';
import 'moment/locale/zh-cn'

import UEditor from 'components/Editor/Editor';
import NavDom from 'components/NavDom/NavDom';
import url from 'api/api';
import storage from 'utils/storage'
import RequestTools from 'utils/request'
import { useNavigate, useLocation } from "react-router-dom";
import './articleAdd.less'

moment.locale('zh-cn')
const { Option } = Select;
const { TextArea } = Input;

const _req = new RequestTools()


function ArticleEdit() {
    let navigate = useNavigate();

    const stateparams = useLocation().state.record
    console.log('stateparams',stateparams)

    let  is_visible_type = 'block';
    let  is_visible_type_2 = 'none';
    if(stateparams.type !== 1 && stateparams.type !== '1'){
        is_visible_type = 'none'
        is_visible_type_2 = 'block'
    }

    const [editorContent, setEditorContent] = useState(stateparams.content);
    const [type, setType] = useState(parseInt(stateparams.type));
    const [status, setStatus] = useState(0);
    const [visible_type, setVisible_type] = useState(is_visible_type);
    const [visible_type_2, setVisible_type_2] = useState(is_visible_type_2);

    let fileListOld = []
    let cover_imageOld = ''
    if(stateparams.thumb !== ''){
        console.log(stateparams.thumb)
        console.log(stateparams.cover_image)
        fileListOld = [
            {
                uid: '-1',
                name: 'image.png',
                status: 'done',
                url: stateparams.thumb,
            }]
        console.log(fileListOld)
        cover_imageOld = stateparams.cover_image
    }
    const [cover_image, setCover_image] = useState(cover_imageOld);
    const [fileList, setFileList] = useState(fileListOld);

    let defaultAttachList = []
    let attachOld = ''
    if(stateparams.attach !== ''){
        defaultAttachList = [
            {
                uid: '-1',
                name: '附件',
                status: 'done',
                url: stateparams.attach_url,
            }]
        console.log('defaultAttachList',defaultAttachList)
        attachOld = stateparams.attach

    }
    const [attach, setAttach] = useState(attachOld);


    const options = JSON.parse(storage.get('category'))
    const tags = JSON.parse(storage.get('tags'))
    let category = [stateparams.category_id,stateparams.p_id];

    const children = [];
    for (let i in tags) {
        children.push(<Option key={i} value={i}>{tags[i]}</Option>);
    }
    console.log('children',children)

    const props = {
        name: 'file',
        action: url['doUploadAttach'],
        headers: {
            authorization: 'authorization-text',
        },
        data:{
            token:storage.get('token')
        },
        defaultFileList:defaultAttachList,
        onChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (info.file.status === 'done') {
                console.log(info.file)
                setAttach(info.file.response.data.file)
                message.success(`${info.file.name} 上传成功`);
            } else if (info.file.status === 'error') {
                message.error(`${info.file.name} 上传失败`);
            }
        },
    };

    // 错误提示
    const error = (val) => {
        message.error(val);
    };
    // 成功提示
    const success = (val) => {
        message.success(val);
    };

    const onEditorChange = (editorContent) => {
        setEditorContent(editorContent)
    };

    const onChangeType = (e) => {
        console.log('onChangeType',e)
        setType(e.target.value)
        if(e.target.value === '1' || e.target.value === 1){
            setVisible_type('block')
            setVisible_type_2('none')
        }else{
            setVisible_type('none')
            setVisible_type_2('block')
        }
    }

    const onChangeTags = (e) => {
        console.log(e);
    }

    const onFileChange = ({ file,event,fileList: newFileList }) => {
        console.log('上传返回的信息')
        console.log(file)
        console.log(file.status)
        if(file.status === 'done' && file.response.code === 0){
            console.log(file.response.code)
            console.log(file.response.data.file)
            setCover_image(file.response.data.file)
        }
        setFileList(newFileList);

    };

    const onPreview = async file => {
        let src = file.url;
        if (!src) {
            src = await new Promise(resolve => {
                const reader = new FileReader();
                reader.readAsDataURL(file.originFileObj);
                reader.onload = () => resolve(reader.result);
            });
        }
        const image = new Image();
        image.src = src;
        const imgWindow = window.open(src);
        imgWindow.document.write(image.outerHTML);
    };


    const onSubmit = (e) =>{
        console.log(1122)
        setStatus(1)
    }

    const onSubmitTest = (e) =>{
        console.log(112212)

        setStatus(0)
    }

    // 添加
    const onAddFinish = values => {

        console.log('Received values of form: ', values);
        var params = {};
        params.id=stateparams.id;
        params.title=values.title;
        params.category=JSON.stringify(values.category);
        params.author=values.author;
        params.tags=JSON.stringify(values.tags);
        params.tags_2=values.tags_2;
        params.description=values.description;

        params.type=type;
        params.content=editorContent?editorContent:'';
        params.source_url=values.source_url?values.source_url:'';
        params.thumb=cover_image;
        params.attach=attach;
        params.status=status;

        console.log('Received params: ', params);

        if(params.type === '1' || params.type === 1){
            if(editorContent === ''){
                error('正文不能为空');
                return false;
            }
        }else{
            if(params.source_url === ''){
                error('原文链接不能为空');
                return false;
            }
        }
        if(cover_image === ''){
            error('封面图必须上传');
            return false;
        }
        _req.axiosPost(params, 'doArticleUpdate').then(res => {
            console.log(res);

            if (res.code===0){
                success(res.data.msg)
                setTimeout(function (){
                    navigate('/app/article',{replace: true})
                },800)
            }else{
                error(res.desc)
            }
        })
    }

    return (
        <div>
            <Row className="list_crumbs">
                <NavDom breads={[{'title':'资讯管理', 'url':'/app/article'},{'title':'资讯编辑', 'url':''}]}/>
            </Row>
            <Row className="list_content">
                <Col span={24}>
                    <Form
                        style={{marginLeft:'-12px'}}
                        labelCol={{ span: 2 }}
                        wrapperCol={{ span: 18 }}
                        layout="horizontal"
                        autoComplete="off"
                        onFinish={onAddFinish}
                        initialValues={{
                            title:stateparams.title,
                            category:category,
                            author:stateparams.author,
                            tags:stateparams.tagsSelected,
                            description:stateparams.description,
                            source_url:stateparams.source_url?stateparams.source_url:''
                        }}
                    >
                        <Form.Item
                            name='title'
                            label="标题"
                            rules={[{required:true,message:'标题必填'}]}
                        >
                            <Input  placeholder="标题"  />
                        </Form.Item>
                        <Form.Item label="分类">
                            <Form.Item
                                name='category'
                                className='article_add_select_category'
                                rules={[{required:true,message:'分类必选'}]}
                            >
                                <Cascader options={options} placeholder="分类" allowClear />
                            </Form.Item>
                            <Form.Item
                                name='author'
                                label="作者"
                                className='article_add_input_author'
                            >
                                <Input placeholder="作者"  />
                            </Form.Item>
                        </Form.Item>
                        <Form.Item
                            label="类型"
                            rules={[{required:true}]}
                        >
                            <Radio.Group name='type' onChange={onChangeType} value={type}>
                                <Radio value={1}>原创</Radio>
                                <Radio value={0}>转载</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item label="标签">
                            <Form.Item
                                name='tags'
                                className='article_add_select_tags'
                                rules={[{required:true,message:'标签必选'}]}
                            >
                                <Select
                                    mode="multiple"
                                    allowClear
                                    placeholder="标签"
                                    onChange={onChangeTags}
                                >
                                    {children}
                                </Select>
                            </Form.Item>
                            <Form.Item
                                name='tags_2'
                                className='article_add_input_tags'
                            >
                                <Input placeholder="自定义标签,使用逗号分割"  />
                            </Form.Item>
                        </Form.Item>
                        <div style={{display:visible_type}}>
                            <Form.Item
                                label="正文"
                            >
                                <UEditor content={editorContent} onChange={onEditorChange} width="600px" height="700px" />
                            </Form.Item>
                        </div>
                        <div style={{display:visible_type_2}}>
                            <Form.Item
                                name='source_url'
                                label="原文链接"
                            >
                                <Input  placeholder="原文链接"  />
                            </Form.Item>
                        </div>
                        <Form.Item
                            label="上传封面图"
                        >
                            <Form.Item
                                name='cover_image'
                                className='article_add_upload_cover'
                            >
                                <ImgCrop rotate>
                                    <Upload
                                        accept="image/*"
                                        action={url['doUploadImg']}
                                        data={{token : storage.get('token')}}
                                        listType="picture-card"
                                        fileList={fileList}
                                        onChange={onFileChange}
                                        onPreview={onPreview}
                                    >
                                        {fileList.length < 1 && '封面图'}
                                    </Upload>
                                </ImgCrop>
                            </Form.Item>
                            <Form.Item
                                name='description'
                                label="摘要"
                                className='article_add_input_description'
                                rules={[{required:true,message:'摘要必填'}]}
                            >
                                <TextArea
                                    rows={4}
                                    placeholder="摘要"
                                    style={{height:104}}
                                />
                            </Form.Item>
                            <Space>提示:建议尺寸640*360像素或比例16:9,格式:jpg、png,小于5M的图片</Space>
                        </Form.Item>

                        <Form.Item  label="附件">
                            <Upload {...props}>
                                <Button icon={<UploadOutlined />}>上传附件</Button>
                            </Upload>
                            <Space>提示:建议格式为word、excel、ppt、pdf,小于10M以内</Space>
                        </Form.Item>

                        <Form.Item className='submitBtn' style={{margin:'20px 0 0 120px '}} >
                            <Button key="submit" type="primary" htmlType="submit" onClick={onSubmit} >
                                提交
                            </Button>
                            <Button >
                                预览
                            </Button>
                            <Button htmlType="submit" onClick={onSubmitTest}>
                                保存草稿
                            </Button>
                        </Form.Item>
                    </Form>
                </Col>
            </Row>
        </div>
    )
}

export default ArticleEdit


打赏

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

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

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

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