剧场模式
首页前端react 基础实践篇-小型财务系统

react 基础实践篇-小型财务系统 #8 更新 Record

下载源码hfpp2012发布于React4780 次点击播放时长:20:41
6

注意,请求使用的方法是 put,而不是 post。

http://www.mockapi.io/

https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html

此次代码更改:https://github.com/hfpp2012/react-accounts-app/commit/96f815c24c44e9b4cea394ed87dabd61a624c62b

src/components/Record.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import * as RecordsAPI from '../utils/RecordsAPI';

export default class Record extends Component {
  constructor() {
    super();
    this.state = {
      edit: false
    };
  }

  handleToggle() {
    this.setState({
      edit: !this.state.edit
    });
  }

  handleEdit(event) {
    event.preventDefault();
    const record = {
      date: this.refs.date.value,
      title: this.refs.title.value,
      amount: Number.parseInt(this.refs.amount.value, 0)
    }
    RecordsAPI.update(this.props.record.id, record).then(
      response => {
        this.props.handleEditRecord(this.props.record, response.data);
      }
    ).catch(
      error => console.log(error.message)
    )
  }

  recordRow() {
    return (
      <tr>
        <td>{this.props.record.date}</td>
        <td>{this.props.record.title}</td>
        <td>{this.props.record.amount}</td>
        <td>
          <button className="btn btn-info mr-1" onClick={this.handleToggle.bind(this)}>Edit</button>
          <button className="btn btn-danger">Delete</button>
        </td>
      </tr>
    );
  }

  recordForm() {
    return (
      <tr>
        <td><input type="text" className="form-control" defaultValue={this.props.record.date} ref="date" /></td>
        <td><input type="text" className="form-control" defaultValue={this.props.record.title} ref="title" /></td>
        <td><input type="text" className="form-control" defaultValue={this.props.record.amount} ref="amount" /></td>
        <td>
          <button className="btn btn-info mr-1" onClick={this.handleEdit.bind(this)}>Update</button>
          <button className="btn btn-danger" onClick={this.handleToggle.bind(this)}>Cancel</button>
        </td>
      </tr>
    );
  }

  render() {
    if (this.state.edit) {
      return this.recordForm();
    } else {
      return this.recordRow();
    }
  }
}

Record.propTypes = {
  record: PropTypes.object
}

src/components/Records.js

import React, { Component } from 'react';
import Record from './Record';
import * as RecordsAPI from '../utils/RecordsAPI';
import RecordForm from './RecordForm';

class Records extends Component {
  constructor() {
    super();
    this.state = {
      error: null,
      isLoaded: false,
      records: []
    }
  }

  componentDidMount() {
    RecordsAPI.getAll().then(
      response => this.setState({
        records: response.data,
        isLoaded: true
      })
    ).catch(
      error => this.setState({
        isLoaded: true,
        error
      })
    )
  }

  addRecord(record) {
    this.setState({
      error: null,
      isLoaded: true,
      records: [
        ...this.state.records,
        record
      ]
    })
  }

  updateRecord(record, data) {
    const recordIndex = this.state.records.indexOf(record);
    const newRecords = this.state.records.map( (item, index) => {
      if(index !== recordIndex) {
        // This isn't the item we care about - keep it as-is
        return item;
      }

      // Otherwise, this is the one we want - return an updated value
      return {
        ...item,
        ...data
      };
    });
    this.setState({
      records: newRecords
    });
  }

  render() {
    const { error, isLoaded, records } = this.state;
    let recordsComponent;

    if (error) {
      recordsComponent = <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      recordsComponent = <div>Loading...</div>;
    } else {
      recordsComponent = (
        <table className="table table-bordered">
          <thead>
            <tr>
              <th>Date</th>
              <th>Title</th>
              <th>Amount</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            {records.map((record) => <Record key={record.id} record={record} handleEditRecord={this.updateRecord.bind(this)} />)}
          </tbody>
        </table>
      );
    }

    return (
      <div>
        <h2>Records</h2>
        <RecordForm handleNewRecord={this.addRecord.bind(this)} />
        {recordsComponent}
      </div>
    );
  }
}

export default Records;
10 条回复
  • BaoXiaoShuai
    BaoXiaoShuai #1

    那是不是直接在获取一次列表更保准数据呢?虽然多了一次请求

  • hfpp2012
    hfpp2012 #2

    可以的

  • Amazinghua
    Amazinghua #3

    请问为什么update后刷新页面才会更新数据?

  • hfpp2012
    hfpp2012 #4
    Amazinghua Amazinghua #10 回复

    state 的值没改变 而请求发送了 看下操作 state 变化的地方是不是出错了

  • Amazinghua
    Amazinghua #5
    hfpp2012 hfpp2012 #10 回复

    this.setState({edit:false}); 加上这行改变状态好了谢谢!

  • yang_ye
    yang_ye #6

    视频里的
    updateRecord(record, data) {
    const recordIndex = this.state.records.indexOf(record);
    const newRecords = this.state.records.map( (item, index) => {
    if(index !== recordIndex) {
    // This isn't the item we care about - keep it as-is
    return item;
    }

      // Otherwise, this is the one we want - return an updated value
      return {
        ...item,
        ...data
      };
    });
    this.setState({
      records: newRecords
    });
    

    }

    自己写的
    updateRecord(data, i) {
    let records = [...this.state.records];
    records[i] = {...record[i],...data};
    this.setState({
    records: records
    })
    }

    老大,视频里写的和我这样写的比,有什么好处吗,为什么要用map方法啊

  • hfpp2012
    hfpp2012 #7
    yang_ye yang_ye #10 回复

    你那样其实也可以吧?只是写成 map 不会修改原来的 state 的内容,以后在学习 redux 课程的时候,是不修改 state 内容的,所以这里先这样写

  • yang_ye
    yang_ye #8
    hfpp2012 hfpp2012 #10 回复

    哦,懂了懂了,谢谢

  • cjcj5438
    cjcj5438 #9

    const recordIndex = this.state.records.indexOf(oldRecord)
    这个不是检索字符串的方法吗? 能这样用?

  • hfpp2012
    hfpp2012 #10
    cjcj5438 cjcj5438 #10 回复

    能啊,谁说是针对字符串,数组也可以,不要局限于呀

购买或订阅扫码加我微信
微信二维码

加我微信:15014006126

支付宝付款
友情提示
   官方 QQ 1 群 697272886(500/2000)
   官方 QQ 2 群 856141852
相似的视频
react 基础实践篇-小型财务系统 #10 统计金额(完结)

react 基础实践篇-小型财务系统 #10 统计金额(完结)

免费播放时长:09:29

2905 次点击

react 基础实践篇-小型财务系统 #9 删除 Record

react 基础实践篇-小型财务系统 #9 删除 Record

免费播放时长:06:12

2321 次点击

react 基础实践篇-小型财务系统 #2 实现 records 列表页

react 基础实践篇-小型财务系统 #2 实现 records 列表页

免费播放时长:12:26

4501 次点击

react 基础实践篇-小型财务系统 #1 简介

react 基础实践篇-小型财务系统 #1 简介

免费播放时长:04:12

19616 次点击

© Rails365 | 隐私条款 | 服务条款 | 粤ICP备15004902号 | 在线学员:32

Top