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

react 基础实践篇-小型财务系统 #7 发送 API 请求创建 Record

海外散仙厉飞雨 · 真仙发布于

http://www.mockapi.io/

诱人的 react 视频教程 - 基础篇 #11 子组件向父组件传值 https://www.rails365.net/movies/you-ren-de-react-shi-pin-jiao-cheng-ji-chu-pian-11-zi-zu-jian-xiang-fu-zu-jian-chuan-zhi

src/componets/RecordForm.js

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

export default class RecordForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      date: "",
      title: "",
      amount: ""
    }
  }

  handleChange(event) {
    let name, obj;
    name = event.target.name;
    this.setState((
      obj = {},
      obj["" + name] = event.target.value,
      obj
    ))
  }

  valid() {
    return this.state.date && this.state.title && this.state.amount
  }

  handleSubmit(event) {
    event.preventDefault();

    const data = {
      date: this.state.date,
      title: this.state.title,
      amount: Number.parseInt(this.state.amount, 0)
    };

    RecordsAPI.create(data).then(
      response => {
        this.props.handleNewRecord(response.data);
        this.setState({
          date: "",
          title: "",
          amount: ""
        })
      }
    ).catch(
      error => console.log(error.message)
    )
  }

  render() {
    return (
      <form className="form-inline mb-3" onSubmit={this.handleSubmit.bind(this)}>
        <div className="form-group mr-1">
          <input type="text" className="form-control" onChange={this.handleChange.bind(this)} placeholder="Date" name="date" value={this.state.date} />
        </div>
        <div className="form-group mr-1">
          <input type="text" className="form-control" onChange={this.handleChange.bind(this)} placeholder="Title" name="title" value={this.state.title} />
        </div>
        <div className="form-group mr-1">
          <input type="text" className="form-control" onChange={this.handleChange.bind(this)}  placeholder="Amount" name="amount" value={this.state.amount} />
        </div>
        <button type="submit" className="btn btn-primary" disabled={!this.valid()}>Create Record</button>
      </form>
    );
  }
}

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
      ]
    })
  }

  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>
            </tr>
          </thead>
          <tbody>
            {records.map((record) => <Record key={record.id} {...record} />)}
          </tbody>
        </table>
      );
    }

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

export default Records;
9 条回复
  • Alazyer · 真仙
    Alazyer · 真仙 #1

    老大 你这平台注册验证码 看的我眼疼,弄了小半天

  • zbx7858 · 道祖
    zbx7858 · 道祖 #2

    一定支持,谢谢(●'◡'●)

  • WebGhan · 金仙后期

    老师,怎么解决连续多次点击导致重复提交的问题?

  • 海外散仙厉飞雨 · 真仙

    有两种解决方法,在按钮上入手,点击之后,按钮变灰,不可点状态,提示“正在提交中。。”,类似这样的,来处理。 还有一种可以使用 redux-saga,有个方法可以使用最后一次提交,前面有进行中的提交,会自动被取消掉,也就是对任务有更细颗粒度的控制,可以继续看后面的课程。

  • WebGhan · 金仙后期

    谢谢老师,思路我明白了,可是我目前水平较低,第一种方法有没有代码可以参考。

  • bigOtopus · 真仙
    bigOtopus · 真仙 #6

    老师!数据点击提交后报这个错怎么办……

  • 海外散仙厉飞雨 · 真仙

    你把那个错误复制出来

  • bigOtopus · 真仙
    bigOtopus · 真仙 #8

    错误信息:Uncaught Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development.

  • 海外散仙厉飞雨 · 真仙

    <script crossorigin src="..."></script> https://reactjs.org/docs/cross-origin-errors.html 加上 crossorigin 试试

© 汕尾市求知科技有限公司 | 粤ICP备19038915号 | 在线学员:32

Top