当前位置:   article > 正文

订单管理系统代码(前端React,后端Flask,数据库MongoDb)实现增删改查

订单管理系统代码(前端React,后端Flask,数据库MongoDb)实现增删改查

前端:

App.jsx

  1. import React from 'react';
  2. import './App.css';
  3. import OrderList from './components/OrderList';
  4. function App() {
  5. return (
  6. <div className="App">
  7. <header className="App-header">
  8. <h1>订单管理系统</h1>
  9. </header>
  10. <OrderList />
  11. </div>
  12. );
  13. }
  14. export default App;

OrderList.jsx

  1. import React, { useState, useEffect } from 'react';
  2. import axios from 'axios';
  3. import OrderForm from './OrderForm';
  4. import OrderItem from './OrderItem';
  5. const OrderList = () => {
  6. const [orders, setOrders] = useState([]);
  7. const [query, setQuery] = useState('');
  8. const [editingOrder, setEditingOrder] = useState(null);
  9. useEffect(() => {
  10. fetchOrders();
  11. }, []);
  12. const fetchOrders = async () => {
  13. try {
  14. const response = await axios.get('/api/orders');
  15. setOrders(response.data);
  16. } catch (error) {
  17. console.error('获取订单错误', error);
  18. }
  19. };
  20. const searchOrder = async (e) => {
  21. e.preventDefault();
  22. if (!query) {
  23. fetchOrders();
  24. return;
  25. }
  26. try {
  27. const response = await axios.get(`/api/orders/${query}`);
  28. setOrders(response.data ? [response.data] : []);
  29. } catch (error) {
  30. console.error('查询订单错误', error);
  31. setOrders([]);
  32. }
  33. };
  34. const startEditOrder = (order) => {
  35. setEditingOrder(order);
  36. };
  37. const cancelEditOrder = () => {
  38. setEditingOrder(null);
  39. };
  40. const handleOrderUpdate = async (updatedOrder) => {
  41. try {
  42. await axios.put(`/api/orders/${updatedOrder._id}`, updatedOrder);
  43. fetchOrders();
  44. setEditingOrder(null);
  45. } catch (error) {
  46. console.error('更新订单错误', error);
  47. }
  48. };
  49. return (
  50. <div>
  51. <OrderForm fetchOrders={fetchOrders} />
  52. <form onSubmit={searchOrder}>
  53. <input
  54. type="text"
  55. placeholder="根据订单号查询"
  56. value={query}
  57. onChange={(e) => setQuery(e.target.value)}
  58. />
  59. <button type="submit">查询</button>
  60. </form>
  61. <div className="table-container">
  62. <table>
  63. <thead>
  64. <tr>
  65. <th>订单号</th>
  66. <th>订单名称</th>
  67. <th>数量</th>
  68. <th>操作</th>
  69. </tr>
  70. </thead>
  71. <tbody>
  72. {orders.map(order => (
  73. <OrderItem
  74. key={order._id}
  75. order={order}
  76. fetchOrders={fetchOrders}
  77. startEditOrder={startEditOrder}
  78. />
  79. ))}
  80. </tbody>
  81. </table>
  82. </div>
  83. {editingOrder && (
  84. <OrderForm
  85. order={editingOrder}
  86. handleOrderUpdate={handleOrderUpdate}
  87. cancelEditOrder={cancelEditOrder}
  88. />
  89. )}
  90. </div>
  91. );
  92. };
  93. export default OrderList;

OrderItem.jsx

  1. import React from 'react';
  2. import axios from 'axios';
  3. const OrderItem = ({ order, fetchOrders, startEditOrder }) => {
  4. const deleteOrder = async () => {
  5. try {
  6. await axios.delete(`/api/orders/${order._id}`);
  7. fetchOrders();
  8. } catch (error) {
  9. console.error('删除订单错误', error);
  10. }
  11. };
  12. return (
  13. <tr>
  14. <td>{order._id}</td>
  15. <td>{order.name}</td>
  16. <td>{order.quantity}</td>
  17. <td>
  18. <button onClick={() => startEditOrder(order)}>编辑</button>
  19. <button onClick={deleteOrder}>删除</button>
  20. </td>
  21. </tr>
  22. );
  23. };
  24. export default OrderItem;

OrderForm.jsx

  1. import React, { useState, useEffect } from 'react';
  2. import axios from 'axios';
  3. const OrderForm = ({ fetchOrders, order, handleOrderUpdate, cancelEditOrder }) => {
  4. const [formData, setFormData] = useState({ name: '', quantity: '' });
  5. useEffect(() => {
  6. if (order) {
  7. setFormData(order);
  8. }
  9. }, [order]);
  10. const handleChange = e => {
  11. const { name, value } = e.target;
  12. setFormData({ ...formData, [name]: value });
  13. };
  14. const handleSubmit = async e => {
  15. e.preventDefault();
  16. if (order) {
  17. handleOrderUpdate(formData);
  18. } else {
  19. try {
  20. await axios.post('/api/orders', formData);
  21. fetchOrders();
  22. setFormData({ name: '', quantity: '' });
  23. } catch (error) {
  24. console.error('创建订单错误', error);
  25. }
  26. }
  27. };
  28. return (
  29. <form onSubmit={handleSubmit}>
  30. <input name="name" value={formData.name} onChange={handleChange} placeholder="订单名称" />
  31. <input name="quantity" value={formData.quantity} onChange={handleChange} placeholder="数量" />
  32. <button type="submit">{order ? '更新订单' : '添加订单'}</button>
  33. {order && <button type="button" onClick={cancelEditOrder}>取消</button>}
  34. </form>
  35. );
  36. };
  37. export default OrderForm;

后端:

app.py

  1. from flask import Flask, request, jsonify
  2. from flask_pymongo import PyMongo
  3. from bson.objectid import ObjectId
  4. import os
  5. app = Flask(__name__)
  6. app.config["MONGO_URI"] = os.getenv('MONGO_URI', "mongodb://localhost:27017/orders")
  7. mongo = PyMongo(app)
  8. @app.route('/api/orders', methods=['GET'])
  9. def get_orders():
  10. orders = mongo.db.orders.find()
  11. result = []
  12. for order in orders:
  13. order['_id'] = str(order['_id'])
  14. result.append(order)
  15. return jsonify(result)
  16. @app.route('/api/orders/<id>', methods=['GET'])
  17. def get_order(id):
  18. order = mongo.db.orders.find_one({'_id': ObjectId(id)})
  19. if order:
  20. order['_id'] = str(order['_id'])
  21. return jsonify(order)
  22. else:
  23. return jsonify(message="订单未找到"), 404
  24. @app.route('/api/orders', methods=['POST'])
  25. def add_order():
  26. data = request.json
  27. mongo.db.orders.insert_one(data)
  28. return jsonify(message="订单已添加"), 201
  29. @app.route('/api/orders/<id>', methods=['PUT'])
  30. def update_order(id):
  31. data = request.json
  32. if '_id' in data:
  33. del data['_id'] # 删除 _id 字段以避免修改它
  34. mongo.db.orders.update_one({'_id': ObjectId(id)}, {'$set': data})
  35. return jsonify(message="订单已更新")
  36. @app.route('/api/orders/<id>', methods=['DELETE'])
  37. def delete_order(id):
  38. mongo.db.orders.delete_one({'_id': ObjectId(id)})
  39. return jsonify(message="订单已删除")
  40. if __name__ == '__main__':
  41. app.run(debug=True)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/653746
推荐阅读
相关标签
  

闽ICP备14008679号