React快速开发迷你记账簿------day07 发送api请求 创建record

src/components/RecordForm.js

使用mr -1更改间距(bootstrap 语法)

    ...
render() {
        return (
          <form className = "form-inline mb-3">
              <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>
        )
    }
    ...

更改后刷新页面如下

  • 本节目标:在输入框输入值,点击按钮后,在下方表单显示

    1. 发送创建 record请求(实例化数据)
    2. 更新 列表 Records Component 的state的 records值

    提交请求 三个数据到api 中 返回一个id

  • 1.发送创建 record请求(实例化数据)

    这里是手动设置state,涉及到 父子组件的传值问题

  • 绑定formonSubmit属性为handleSubmit()

  • ...
    handleSubmit(event){
        event.preventDefault();//阻止浏览器的get请求,即现在是post方式
    }
    render() {
            return (
              <form className = "form-inline mb-3" onSubmit={this.handleSubmit.bind(this)}>
                  ...
              </form>
            )
        }
    }
    
  • 阻止了get请求

    src/utils/RecordsAPI.js创建API:

  • ...
    export const getAll = () =>
      axios.get(`${api}/api/v1/records`)
    //添加下面的方法,传入的参数是body,如果并不懂,可以搜索下面的方法
    export const create = (body) =>
      axios.post(`${api}/api/v1/records`, body)
    
  • 回到src\components\RecordForm.js:

  • ...
    import React, { Component } from 'react';
    import * as RecordsAPI from '../utils/RecordsAPI';
    export default class RecordForm extends Component {
    ...
    handleSubmit(event) {
        event.preventDefault();//阻止浏览器的get请求,即现在是post方式
         // this.state
        //相当于{date:this.state.date, 				   title:this.state.title,amount:this.state.amount}
        RecordsAPI.create(this.state).then(response =>
          response => console.log(response.data)
        ).catch(error => console.log(error.message)
        )
      }
    ...
    }
    

    更正错误

    src\components\Record.js:

    import React, { Component } from 'react';
    import PropTypes from 'prop-types' ;//添加这一行导入静态检查的库
    export default class Record extends Component {
        render() {
            return (
                <tr>
                    <td>{this.props.date}</td>
                    <td>{this.props.title}</td>
                    <td>{this.props.amount}</td>
                </tr>
            )
        }
    }
    
    Record.propTypes = {
        id:PropTypes.string,//更改id 为string
        date:PropTypes.string,
        title:PropTypes.string,
        amount:PropTypes.number
    }
    

    id这里返回的是字符串,需要的是number

  • 填入输入框的值默认都是string

    • 这里还是将类型改为string类型
    • 这里我们使用Number.parseInt()将string转化为整形变量,第二个参数是 0 表示将其转化为10进制

修改src\components\RecordForm.js:为

...
import React, { Component } from 'react';
import * as RecordsAPI from '../utils/RecordsAPI';
export default class RecordForm extends Component {
...
handleSubmit(event) {
    event.preventDefault();//阻止浏览器的get请求,即现在是post方式
     // this.state
    //相当于{date:this.state.date, 				   title:this.state.title,amount:this.state.amount}
    RecordsAPI.create({date:this.state.date, title:this.state.title,amount:Number.parseInt(this.state.amount,0)}).then(response =>
      response => console.log(response.data)
    ).catch(error => console.log(error.message)
    )
  }
...
}

上面的写法太长了进行如下更改

 handleSubmit(event) {
    event.preventDefault();//阻止浏览器的get请求,即现在是post方式
    //上面的写法太长了  使用下面的写法
    const data = {
      date:this.state.date, 
      title:this.state.title,
      amount:Number.parseInt(this.state.amount,0)
    }
    RecordsAPI.create(data).then( 
        response => console.log(response.data)
    ).catch(error => console.log(error.message)
   ) 
  }
  • 2.更新 列表 Records Component 的state的 records值

    (子父组件传值)

      1. 创建addRecord()这个函数

      2. 修改src\components\RecordForm.js:为

        添加这个函数,更新列表 isLoaded:true:更新过列表

        ...this.state.records 扩展符号,将records展开

      3. 更新功能:将传过来的record...this.state.records合并到records

          ...
          addRecord(record){
              //得到传入的值
              //console.log(record);
              this.setState({
              error:null,
              isLoaded:true,
              records:[
                  ...this.state.records,
                  record
              ]
              })
           }
          ...
        
      4. 绑定this.props.handleNewRecord并添加清空功能

        handleSubmit(event) {
            event.preventDefault();//阻止浏览器的get请求,即现在是post方式
            //上面的写法太长了  使用下面的写法
            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)
           ) 
          }
        
  1. 添加更新表单的功能,设置状态,将records合并

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() {...}
  
    componentDidMount() {...}
    
    addRecord(record){
      //得到传入的值
      //console.log(record);
      this.setState({
      error:null,
      isLoaded:true,
      records:[
          ...this.state.records,
          record
      ]
      })
   }
    render() {...}
      return (
        <div>
              <h2>Records</h2>
              <RecordForm handleNewRecord = {this.addRecord.bind(this)}/>
              {recordsComponents}
        </div>
      )
  
    }
  }
  export default Records;

补充知识点:

   //将a和b混在一起
    //a是一个数字里面有两个对象
    //b有一个对象
    //将a 展开和b放入c的数组中
    const a = [{"a" : "b"},{"c":"d"}];
    const b = {"e":"f"};
    const c =[
      ...a,
      b
    ]
    console.log(c)//[{"a" : "b"},{"c":"d"}, {"e":"f"}]

至此,就完成了自动清空和更新的功能.

day07

完整项目代码:

Edit 07_require(record)

https://github.com/lenvo222/07_require_record.git

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小李科技

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值