世界上最伟大的投资就是投资自己的教育


id 10529

cingzion


惠赠 投资者 JACKY 1 days 14 hours 59 minutes 44 seconds 舵主 研究生 移动端用户


  • React 基础实践篇免费视频教程 - 小型财务系统 #9 删除 Record

    按老师的方法,实现真正的删除,如果大家发现不能删除成功和更新,一定要多仔细的多看几次,只到会和实现,再看下一节。这样才能学到老师讲的技术点,这只是我个人的观点。

    // 接口  src\utils\RecordsAPI.js
    import axios from "axios";
    
    // 环境
    const api = process.env.REACT_APP_RECORDS_API_URL || "http://5d712b7ad3448a001411b5c2.mockapi.io";
    
    // 查询
    export const getAll = () => axios.get(`${api}/api/v1/recores`);
    
    // 增加
    export const create = (body) => axios.post(`${api}/api/v1/recores`, body);
    
    // 更新
    export const update = (id,body) => axios.post(`${api}/api/v1/recores/${id}`, body);
    
    // 删除
    export const remove = (id) => axios.delete(`${api}/api/v1/recores/${id}`);
    
    
    // .env.development.local
    REACT_APP_RECORDS_API_URL=http://5d712b7ad3448a001411b5c2.mockapi.io
    
    
    
    //src\index.js
    
    // src\components\Records\index.js
    import React, {Component} from 'react';
    // import { getJSON } from 'jquery';
    // import axios from 'axios';
    import Record from '../Record';
    import RecordForm from '../RecordForm';
    import * as RecordsAPI from '../../utils/RecordsAPI';
    
    
    class Records extends Component {
        state = {
            error: null,
            isLoaded: false,
            recores: []
        }
    
        componentDidMount() {
            // 使用 jquery
    
            /*getJSON('http://5d712b7ad3448a001411b5c2.mockapi.io/api/v1/recores').then((response) => {
                return this.setState({
                    recores:response,
                    isLoaded: true,
                });
            }, error => {
                this.setState({
                    isLoaded: true,
                    error: error.responseText,
                });
            });*/
    
            // 使用 axios
    
            /*axios.get('http://5d712b7ad3448a001411b5c2.mockapi.io/api/v1/recores').then((response) => {
                return this.setState({
                    recores:response.data,
                    isLoaded: true,
                });
            }).catch(error => {
                this.setState({
                    isLoaded: true,
                    error: error.message,
                });
            });*/
            this.handleRecordsAPI();
    
        }
    
        handleRecordsAPI = () => {
    
            RecordsAPI.getAll().then((response) => {
                return this.setState({
                    recores: response.data,
                    isLoaded: true,
                });
            }).catch(error => {
                this.setState({
                    isLoaded: true,
                    error: error.message,
                });
            });
        };
    
    
        addRecord = (record) => {
            console.log(record);
            // this.handleRecordsAPI();
            this.setState({
                error: null,
                isLoaded: true,
                recores: [
                    ...this.state.recores,
                    record
                ]
            })
        }
    
        // 更新当前的编辑值
        handleEditRecord = (record, data) => {
    
            console.log("record",record);
    
            /*
            const a = {a: 'b'};
            const b = {a: 'c'};
            const c = {
                ...a,   // 旧的值
                ...b,   // 新的值
            };
    
            console.log('c',c);  // 返回过来的值 c {a: "c"}
            */
    
    
            // 当前的位置
            const recordInex = this.state.recores.indexOf(record);
    
    
    
            const newRecords = this.state.recores.map((item, index) => {
                if(index !== recordInex){
                    return item;
                }
    
                return {
                    ...item,
                    ...data
                }
            });
    
    
            this.setState({
                recores: newRecords,
            });
    
        }
    
        // 删除
        handleDeleteRecord = (record) => {
            // 当前的位置
            const recordInex = this.state.recores.indexOf(record);
    
            // 移出一个元素
            const newRecords = this.state.recores.filter((item, index) => index !== recordInex);
            this.setState({
    
            });
            this.setState({
                recores: newRecords,
            });
            console.log("删除", record);
    
        }
    
        render() {
    
            const {error, isLoaded, recores} = this.state;
    
            let recordsComponents;
    
    
            // 处理加载中....
            if (error) {
                recordsComponents = <div>Error: {error}</div>
            } else if (!isLoaded) {
                recordsComponents = <div>Loading...</div>
            } else {
                recordsComponents = (
                    <table className="table table-bordered">
                        <thead>
                        <tr>
                            <th>Date</th>
                            <th>Title</th>
                            <th>Amount</th>
                            <th>Actions</th>
                        </tr>
                        </thead>
                        <tbody>
                        {
                            recores.map((record) => {
                                return (
                                    <Record
                                        key={record.id}
                                        record={record}
                                        handleEditRecord={this.handleEditRecord}
                                        handleDeleteRecord={this.handleDeleteRecord}
                                    />
                                );
                            })
                        }
                        </tbody>
                    </table>
                );
            }
    
    
            return (
                <div>
                    <h2>Record</h2>
                    <RecordForm
                        handleRecordsAPI={this.handleRecordsAPI}
                        handleNewRecord={this.addRecord}
                    />
                    { recordsComponents }
                </div>
            );
    
    
        }
    }
    
    export default Records;
    
    
    // src\components\RecordForm\index.js
    import React, {Component} from 'react';
    import * as RecoresAPI from '../../utils/RecordsAPI';
    
    class RecordForm extends Component {
        state = {
            date: '',
            title: '',
            amount: '',
        }
    
    
        valid = () => {
            const {date, title, amount} = this.state;
            // 判断3个同时有值才可以点的
            return date && title && amount;
        }
    
        handleChange = (e) => {
            let name, obj;
            name = e.target.name;
            console.log(e.target.name); // 取name的值
            this.setState((
                obj={},
                obj[`${name}`] = e.target.value,
                obj
            ));
    
            // 以上等价于下面的方法
            /*this.setState({
               [name]: e.target.value
            });*/
    
            console.log(this.state);
        }
    
        handleSubmit = (e) => {
            // 阻止事件
            e.preventDefault();
            const {
                date,
                title,
                amount,
            } = this.state;
            const parmas = {
                date,
                title,
                amount: Number.parseInt(amount, 10),
            };
    
            RecoresAPI.create(parmas).then(response => {
                this.props.handleNewRecord(response.data);
                this.setState({
                    date: '',
                    title: '',
                    amount: '',
                });
    
            }).catch(error => {
                console.log(error);
            });
        }
    
        render() {
            const {date, title, amount} = this.state;
            return (
                <form className="form-inline mb-3" onSubmit={this.handleSubmit}>
                    <div className="form-group mr-1">
                        <input
                            type="text"
                            className="form-control"
                            placeholder="Date"
                            name="date"
                            value={date}
                            onChange={this.handleChange}
                        />
                    </div>
    
                    <div className="form-group mr-1">
                        <input
                            type="text"
                            className="form-control"
                            placeholder="Title"
                            name="title"
                            value={title}
                            onChange={this.handleChange}
                        />
                    </div>
    
                    <div className="form-group mr-1">
                        <input
                            type="text"
                            className="form-control"
                            placeholder="Amount"
                            name="amount"
                            value={amount}
                            onChange={this.handleChange}
                        />
                    </div>
    
                    <button type="submit" disabled={!this.valid()} className="btn btn-primary">Create Record</button>
                </form>
            );
        }
    }
    
    export default RecordForm;
    
    // src\components\Record\index.js
    import React, {Component} from 'react';
    import PropTypes from 'prop-types';
    import * as RecordsAPI from '../../utils/RecordsAPI';
    
    class Record extends Component {
        state = {
            edit: false,
        }
    
        handleToggle = () => {
            const {edit} = this.state;
            this.setState({
                edit: !edit,
            })
        }
    
    
        // 更新
        handleEdit = (e) => {
            e.preventDefault();
            const {id} = this.props.record;
            const targets = this.refs;
    
    
            const record = {
                id,
                date: targets.date.value,
                title: targets.title.value,
                amount: Number.parseInt(targets.amount.value, 10),
            };
    
            RecordsAPI.update(id, record).then(response => {
                this.setState({edit: false});
                this.props.handleEditRecord(this.props.record, response.data);
            }).catch(error => {
                console.log(error.message);
            });
        }
    
        // 删除
        handleDelete = (e) => {
            e.preventDefault();
            const {id} = this.props.record;
    
            RecordsAPI.remove(id).then(response => {
    
                this.props.handleDeleteRecord(this.props.record);
    
            }).catch(error => {
                console.log(error)
            })
        }
    
        recordRow = () => {
            const {date, title, amount} = this.props.record;
            return (
                <tr>
                    <td>{date}</td>
                    <td>{title}</td>
                    <td>{amount}</td>
                    <td>
                        <button className="btn btn-info mr-1" onClick={ this.handleToggle }>Edit</button>
                        <button className="btn btn-danger" onClick={this.handleDelete}>Delete</button>
                    </td>
                </tr>
            );
        }
    
        recordForm = () => {
            const {date, title, amount} = this.props.record;
            return (
                <tr>
                    <td><input type="text" className="form-control" defaultValue={date} ref="date"/></td>
                    <td><input type="text" className="form-control" defaultValue={title} ref="title"/></td>
                    <td><input type="text" className="form-control" defaultValue={amount} ref="amount"/></td>
    
                    <td>
                        <button className="btn btn-info mr-1" onClick={ this.handleEdit }>Update</button>
                        <button className="btn btn-danger" onClick={ this.handleToggle }>Cancel</button>
                    </td>
                </tr>
            );
        }
    
        render() {
            const {edit} = this.state;
            if (edit) {
                return this.recordForm();
            } else {
                return this.recordRow();
            }
        }
    }
    
    Record.propTypes = {
        date: PropTypes.string,
        title: PropTypes.string,
        amount: PropTypes.number,
    };
    
    export default Record;
    
    

© 汕尾市求知科技有限公司 | Rails365 Gitlab | 知乎 | b 站 | csdn

粤公网安备 44152102000088号粤公网安备 44152102000088号 | 粤ICP备19038915号

Top