添加編輯css
刪除 html
npm install -g create-react-app
複製代碼
create-react-app node-react-koa
cd node-react-koa && mkdir server //node服務都放在該文件下
npm run eject //可省略,只爲了看配置 config
npm start
複製代碼
npm install antd --save
複製代碼
npm install axios --save
複製代碼
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
import { Table, Pagination, Input, Row, Button, Modal, Form } from 'antd';
import 'antd/dist/antd.css'
const { Search } = Input;
const FormItem = Form.Item;
const { confirm } = Modal;
class App extends Component {
constructor(props) {
super(props);
}
columns = [{
dataIndex: "username", title: "用戶",
}, {
dataIndex: "age", title: "年齡",
}, {
dataIndex: "address", title: "地址"
}, {
dataIndex: "action", title: "操做", width: 200, render: (text, row) => {
return <div>
<Button onClick={() => this.modal('edit', row)} >編輯</Button>
<Button style={{ marginLeft: 10 }} type="danger" onClick={() => this.remove(row)} >刪除</Button>
</div>
}
}];
state = {
dataSource: [{ username: "slf", age: "18", address: "杭州", id: 1 }],
current: 1,
size: 10,
total: 1,
visible: false,
modalType: "add"
}
componentDidMount() {
this.sizeChange(this.state.current,this.state.size);
}
//分頁
sizeChange = (current, size) => {
//todo
}
//提交
handleOk = () => {
//todo
}
//添加編輯用戶
modal = (type, row) => {
this.setState({
visible: true,
modalType: type
}, () => {
this.props.form.resetFields();
if (type === 'add') return;
this.props.form.setFieldsValue({
username: row.username,
age: row.age,
address: row.address
})
})
}
remove = (row) => {
confirm({
title: '是否要刪除該用戶?',
okText: '是',
okType: '否',
cancelText: 'No',
onOk() {
//todo
},
onCancel() {
//todo
},
});
}
render() {
const { getFieldDecorator } = this.props.form;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
return (
<div className="App">
<Row>
<Search style={{ width: 300 }} />
<Button type="primary" style={{ marginLeft: 20 }} onClick={() => this.modal('add')} >添加用戶</Button>
</Row>
<Row style={{ paddingTop: 20 }}>
<Table dataSource={this.state.dataSource} rowKey={row => row.id} bordered columns={this.columns} pagination={false} />
</Row>
<Row style={{ paddingTop: 20 }}>
<Pagination
showTotal={(total) => `共 ${total} 條`}
current={this.state.current} total={this.state.total} pageSize={this.state.size}
onChange={this.sizeChange} />
</Row>
<Modal
title={this.state.modalType === 'add' ? "添加用戶" : "編輯用戶"}
onOk={this.handleOk}
onCancel={() => this.setState({ visible: false })}
visible={this.state.visible}
>
<Form>
<FormItem label="用戶" {...formItemLayout}>
{getFieldDecorator('username', {
rules: [{ required: true, message: 'Please input your username!' }],
})(
<Input placeholder="Username" />
)}
</FormItem>
<FormItem label="年齡" {...formItemLayout}>
{getFieldDecorator('age', {
rules: [{ required: true, message: 'Please input your age!' }],
})(
<Input placeholder="age" />
)}
</FormItem>
<FormItem label="地址" {...formItemLayout}>
{getFieldDecorator('address', {
rules: [{ required: true, message: 'Please input your address!' }],
})(
<Input placeholder="address" />
)}
</FormItem>
</Form>
</Modal>
</div >
);
}
}
export default Form.create()(App);
複製代碼
npm install koa koa-body koa-cors koa-router sequelize mysql2 --save
複製代碼
在server目錄下面新建如下內容:前端
node server/app.js
/server/app.jsnode
const Koa = require('koa');
const cors = require('koa-cors');
const router = require('./routers/index')
// 建立一個Koa對象表示web app自己:
const app = new Koa();
app.use(cors());//解決跨域問題
// 對於任何請求,app將調用該異步函數處理請求:
app.use(async (ctx, next) => {
console.log(ctx.request.path + ':' + ctx.request.method);
await next();
});
app.use(router.routes());
app.listen(3005);
console.log('app started at port 3005...');
複製代碼
/server/model/index.jsmysql
const Sequelize = require('sequelize');
const sequelize = new Sequelize('數據庫名', '用戶名', '密碼', {
host: 'localhost',
dialect: 'mysql',
operatorsAliases: true,
pool: {
max: 5, min: 0, acquire: 30000, idle: 10000
},
define: {
timestamps: false,
},
})
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
module.exports = sequelize;
複製代碼
根據表設計react
/server/model/user.jsios
sequelize 點擊可看使用方式git
/server/model/user.js
const Sequelize = require('sequelize')
const sequelize = require('./index')
const User = sequelize.define('userinfos', {
id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true, unique: true },
username: { type: Sequelize.STRING },
age:{type:Sequelize.INTEGER},
address: { type: Sequelize.STRING },
isdelete: { type: Sequelize.INTEGER, allowNull: true }//軟刪除 0爲未刪除,1爲刪除
});
module.exports = User;
複製代碼
由於項目小,我就寫在了routers目錄內。github
/routers/index.js
複製代碼
const koaBody = require('koa-body');
const router = require('koa-router')();
const User = require('../model/user');
複製代碼
router.get('/users', async (ctx, next) => {
const user = await User.findAll({
where: { isdelete: 0 },
})
ctx.body = user;
});
複製代碼
運行web
node server/app.js
複製代碼
postman 測試
成功!
1.增長用戶 先回到src/App.js,完善添加提交方法
handleOk = () => {
this.props.form.validateFieldsAndScroll((err, value) => {
if (err) return;
let data = {
username: value.username, age: value.age, address: value.address
};
if (this.state.modalType === 'add') {
axios.post("http://127.0.0.1:3005/user", data)
.then(msg => {
this.sizeChange(this.state.current, this.state.size);
this.setState({visible: false});
message.success('success!')
})
} else {
axios.put("http://127.0.0.1:3005/user/" + this.state.editRow.id, data)
.then(data => {
this.sizeChange(this.state.current, this.state.size);
this.setState({visible: false});
message.success('success!')
})
}
})
}
複製代碼
2.添加api server/routers/index.js
router.post('/user', koaBody(), async (ctx) => {
const user = await User.build(ctx.request.body).save();
ctx.body = user;
})
複製代碼
3.同理編輯用戶 server/routers/index.js
router.put('/user/:id', koaBody(), async (ctx) => {
const body = ctx.request.body;
const user = await User.findById(ctx.params.id);
await user.update({...body})
ctx.body = user;
})
複製代碼
4.刪除用戶 server/router/index.js
router.delete('/user/:id', async (ctx) => {
const user = await User.findById(ctx.params.id).then((user) => user);
user.isdelete = 1;
await user.save();
ctx.body = { success: true }
})
複製代碼
5.分頁查詢 server/router/index.js
//{"limit":10,"offset":0,"search":"slf"}
router.post('/user-search', koaBody(), async (ctx) => {
const body = ctx.request.body;
const user = await User.findAndCount({
where: {
isdelete: 0, username: {
$like: `%${body.search}%`
}
},
limit: body.limit,
offset: body.offset
});
ctx.body = user;
});
複製代碼
最後
module.exports = router;
複製代碼
完善版前端
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
import {Table, Pagination, Input, Row, Button, Modal, Form, message} from 'antd';
import 'antd/dist/antd.css'
const {Search} = Input;
const FormItem = Form.Item;
const {confirm} = Modal;
class App extends Component {
constructor(props) {
super(props);
}
columns = [{
dataIndex: "username", title: "用戶",
}, {
dataIndex: "age", title: "年齡",
}, {
dataIndex: "address", title: "地址"
}, {
dataIndex: "action", title: "操做", width: 200, render: (text, row) => {
return <div>
<Button onClick={() => this.modal('edit', row)}>編輯</Button>
<Button style={{marginLeft: 10}} type="danger" onClick={() => this.remove(row)}>刪除</Button>
</div>
}
}];
state = {
dataSource: [],
current: 1,
size: 10,
total: 0,
visible: false,
modalType: "add",
search: "",
editRow: {}
}
componentDidMount() {
this.sizeChange(this.state.current, this.state.size);
}
//分頁
sizeChange = (current, size) => {
let data = {
search: this.state.search,
limit: size,
offset: (parseInt(current) - 1) * size
}
axios.post("http://localhost:3005/user-search", data).then(data => {
this.setState({
dataSource: data.data.rows,
total: data.data.count,
current, size
})
})
};
//提交
handleOk = () => {
this.props.form.validateFieldsAndScroll((err, value) => {
if (err) return;
let data = {
username: value.username, age: value.age, address: value.address
};
if (this.state.modalType === 'add') {
axios.post("http://127.0.0.1:3005/user", data)
.then(msg => {
this.sizeChange(this.state.current, this.state.size);
this.setState({visible: false});
message.success('success!')
})
} else {
axios.put("http://127.0.0.1:3005/user/" + this.state.editRow.id, data)
.then(data => {
this.sizeChange(this.state.current, this.state.size);
this.setState({visible: false});
message.success('success!')
})
}
})
}
//添加編輯用戶
modal = (type, row) => {
this.setState({
visible: true,
modalType: type
}, () => {
this.props.form.resetFields();
if (type === 'add') return;
this.props.form.setFieldsValue({
username: row.username,
age: row.age,
address: row.address
})
this.setState({editRow: row})
})
}
remove = (row) => {
let _this = this;
confirm({
title: '是否要刪除該用戶?',
okText: '是',
okType: '否',
cancelText: 'No',
onOk() {
axios.delete("http://127.0.0.1:3005/user/"+row.id)
.then(data=>{
_this.sizeChange(_this.state.current, _this.state.size);
message.success('success!')
})
}
});
};
search = (name) => {
this.setState({
search: name
}, () => {
this.sizeChange(1, 10)
})
};
render() {
const {getFieldDecorator} = this.props.form;
const formItemLayout = {
labelCol: {
xs: {span: 24},
sm: {span: 4},
},
wrapperCol: {
xs: {span: 24},
sm: {span: 16},
},
};
return (
<div className="App">
<Row>
<Search style={{width: 300}} onChange={this.search}/>
<Button type="primary" style={{marginLeft: 20}} onClick={() => this.modal('add')}>添加用戶</Button>
</Row>
<Row style={{paddingTop: 20}}>
<Table dataSource={this.state.dataSource} rowKey={row => row.id} bordered columns={this.columns}
pagination={false}/>
</Row>
<Row style={{paddingTop: 20}}>
<Pagination
showTotal={(total) => `共 ${total} 條`}
current={this.state.current} total={this.state.total} pageSize={this.state.size}
onChange={this.sizeChange}/>
</Row>
<Modal
title={this.state.modalType === 'add' ? "添加用戶" : "編輯用戶"}
onOk={this.handleOk}
onCancel={() => this.setState({visible: false})}
visible={this.state.visible}
>
<Form>
<FormItem label="用戶" {...formItemLayout}>
{getFieldDecorator('username', {
rules: [{required: true, message: 'Please input your username!'}],
})(
<Input placeholder="username"/>
)}
</FormItem>
<FormItem label="年齡" {...formItemLayout}>
{getFieldDecorator('age', {
rules: [{required: true, message: 'Please input your age!'}],
})(
<Input placeholder="age"/>
)}
</FormItem>
<FormItem label="地址" {...formItemLayout}>
{getFieldDecorator('address', {
rules: [{required: true, message: 'Please input your address!'}],
})(
<Input placeholder="address"/>
)}
</FormItem>
</Form>
</Modal>
</div>
);
}
}
export default Form.create()(App);
複製代碼
總結: 我真的很厲害哦(不要臉)