(react)获取json数据与传入(antd配合)
import React from 'react'; import {fetch} from 'whatwg-fetch'; // import {HashRouter as Router,Route,Redirect,Switch} from 'react-router-dom' import { Table,Input,Button,Radio,Modal} from 'antd'; import './index.css'; export default class Home extends React.Component { constructor(props){ super(props) this.state = { columns : [ { title: 'id', dataIndex: 'id', key: 'id' }, { title: '日期', dataIndex: 'date', key: 'date' }, { title: '姓名', dataIndex: 'name', key: 'name' }, { title: '地址', dataIndex: 'address', key: 'address' }, {title: '删除', dataIndex: '',key: 'x',render: () => <a href="javascript:;">Delete</a>,}, ], data:[] , visible: false, id:3, xm:'', dizhi:'', date:'', } } render() { return( <div className='app'> <Table columns={this.state.columns} dataSource={this.state.data} />, <Button className='btn' type="primary" shape="round" onClick={this.showModal} > 添加项目 </Button> <Modal title="录入用户" visible={this.state.visible} onOk={this.handleOk} okText='确认' onCancel={this.handleCancel} cancelText='取消' > <p>姓名:<Input className='inp' placeholder="请输入姓名" onChange={this.xm.bind(this)} /></p> <p>地址:<Input className='inp' placeholder="请输入地址" onChange={this.dz.bind(this)} /></p> </Modal> </div> ) } componentDidMount(){
//获取json里的数据 var that = this; fetch("http://localhost:3000/user", { method: "GET", // headers: { // "Content-Type": "application/json", // }, // mode: "cors", // body: JSON.stringify({ // content: "留言内容" // }) }).then((res)=> res.json() ).then((res)=> { that.setState({ data:res, }) console.log(res) }).catch((err) =>{ console.log(err); }); } xm = (e)=>{ //var that = this; let val = e.target.value; console.log(val) this.setState({ xm:val, val:'' }) } dz = (e)=>{ //var that = this; let val = e.target.value; console.log(val) this.setState({ dz:val, val:'' }) } showModal = () => { this.setState({ visible: true, }); }; handleOk = e => { let date = new Date(); let asd = date.getTime(); let obj={ date:asd, name:this.state.xm, address:this.state.dz, } this.state.data.push(obj) //把写好的数据传入db.json fetch("http://localhost:3000/user", { method: "POST", body: JSON.stringify({ ...obj, }), headers: { "content-type": "application/json" } }) .then(response => response.json()) .then(res => { console.log(res); }); // this.setState({ visible: false, }); }; handleCancel = e => { console.log(e); this.setState({ visible: false, }); }; }