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

前端:

App.jsx

javascript 复制代码
import React from 'react';
import './App.css';
import OrderList from './components/OrderList';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <h1>订单管理系统</h1>
      </header>
      <OrderList />
    </div>
  );
}

export default App;

OrderList.jsx

javascript 复制代码
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import OrderForm from './OrderForm';
import OrderItem from './OrderItem';

const OrderList = () => {
  const [orders, setOrders] = useState([]);
  const [query, setQuery] = useState('');
  const [editingOrder, setEditingOrder] = useState(null);

  useEffect(() => {
    fetchOrders();
  }, []);

  const fetchOrders = async () => {
    try {
      const response = await axios.get('/api/orders');
      setOrders(response.data);
    } catch (error) {
      console.error('获取订单错误', error);
    }
  };

  const searchOrder = async (e) => {
    e.preventDefault();
    if (!query) {
      fetchOrders();
      return;
    }
    try {
      const response = await axios.get(`/api/orders/${query}`);
      setOrders(response.data ? [response.data] : []);
    } catch (error) {
      console.error('查询订单错误', error);
      setOrders([]);
    }
  };

  const startEditOrder = (order) => {
    setEditingOrder(order);
  };

  const cancelEditOrder = () => {
    setEditingOrder(null);
  };

  const handleOrderUpdate = async (updatedOrder) => {
    try {
      await axios.put(`/api/orders/${updatedOrder._id}`, updatedOrder);
      fetchOrders();
      setEditingOrder(null);
    } catch (error) {
      console.error('更新订单错误', error);
    }
  };

  return (
    <div>
      <OrderForm fetchOrders={fetchOrders} />
      <form onSubmit={searchOrder}>
        <input
          type="text"
          placeholder="根据订单号查询"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
        />
        <button type="submit">查询</button>
      </form>
      <div className="table-container">
        <table>
          <thead>
            <tr>
              <th>订单号</th>
              <th>订单名称</th>
              <th>数量</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {orders.map(order => (
              <OrderItem
                key={order._id}
                order={order}
                fetchOrders={fetchOrders}
                startEditOrder={startEditOrder}
              />
            ))}
          </tbody>
        </table>
      </div>
      {editingOrder && (
        <OrderForm
          order={editingOrder}
          handleOrderUpdate={handleOrderUpdate}
          cancelEditOrder={cancelEditOrder}
        />
      )}
    </div>
  );
};

export default OrderList;

OrderItem.jsx

javascript 复制代码
import React from 'react';
import axios from 'axios';

const OrderItem = ({ order, fetchOrders, startEditOrder }) => {
  const deleteOrder = async () => {
    try {
      await axios.delete(`/api/orders/${order._id}`);
      fetchOrders();
    } catch (error) {
      console.error('删除订单错误', error);
    }
  };

  return (
    <tr>
      <td>{order._id}</td>
      <td>{order.name}</td>
      <td>{order.quantity}</td>
      <td>
        <button onClick={() => startEditOrder(order)}>编辑</button>
        <button onClick={deleteOrder}>删除</button>
      </td>
    </tr>
  );
};

export default OrderItem;

OrderForm.jsx

javascript 复制代码
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const OrderForm = ({ fetchOrders, order, handleOrderUpdate, cancelEditOrder }) => {
  const [formData, setFormData] = useState({ name: '', quantity: '' });

  useEffect(() => {
    if (order) {
      setFormData(order);
    }
  }, [order]);

  const handleChange = e => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleSubmit = async e => {
    e.preventDefault();
    if (order) {
      handleOrderUpdate(formData);
    } else {
      try {
        await axios.post('/api/orders', formData);
        fetchOrders();
        setFormData({ name: '', quantity: '' });
      } catch (error) {
        console.error('创建订单错误', error);
      }
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" value={formData.name} onChange={handleChange} placeholder="订单名称" />
      <input name="quantity" value={formData.quantity} onChange={handleChange} placeholder="数量" />
      <button type="submit">{order ? '更新订单' : '添加订单'}</button>
      {order && <button type="button" onClick={cancelEditOrder}>取消</button>}
    </form>
  );
};

export default OrderForm;

后端:

app.py

python 复制代码
from flask import Flask, request, jsonify
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
import os

app = Flask(__name__)
app.config["MONGO_URI"] = os.getenv('MONGO_URI', "mongodb://localhost:27017/orders")
mongo = PyMongo(app)

@app.route('/api/orders', methods=['GET'])
def get_orders():
    orders = mongo.db.orders.find()
    result = []
    for order in orders:
        order['_id'] = str(order['_id'])
        result.append(order)
    return jsonify(result)

@app.route('/api/orders/<id>', methods=['GET'])
def get_order(id):
    order = mongo.db.orders.find_one({'_id': ObjectId(id)})
    if order:
        order['_id'] = str(order['_id'])
        return jsonify(order)
    else:
        return jsonify(message="订单未找到"), 404

@app.route('/api/orders', methods=['POST'])
def add_order():
    data = request.json
    mongo.db.orders.insert_one(data)
    return jsonify(message="订单已添加"), 201

@app.route('/api/orders/<id>', methods=['PUT'])
def update_order(id):
    data = request.json
    if '_id' in data:
        del data['_id']  # 删除 _id 字段以避免修改它
    mongo.db.orders.update_one({'_id': ObjectId(id)}, {'$set': data})
    return jsonify(message="订单已更新")

@app.route('/api/orders/<id>', methods=['DELETE'])
def delete_order(id):
    mongo.db.orders.delete_one({'_id': ObjectId(id)})
    return jsonify(message="订单已删除")

if __name__ == '__main__':
    app.run(debug=True)
相关推荐
o(╥﹏╥)9 分钟前
linux(ubuntu )卡死怎么强制重启
linux·数据库·ubuntu·系统安全
阿里嘎多学长24 分钟前
docker怎么部署高斯数据库
运维·数据库·docker·容器
Yuan_o_26 分钟前
Linux 基本使用和程序部署
java·linux·运维·服务器·数据库·后端
Sunyanhui131 分钟前
牛客网 SQL36查找后排序
数据库·sql·mysql
老王笔记44 分钟前
MHA binlog server
数据库·mysql
顾平安1 小时前
Promise/A+ 规范 - 中文版本
前端
聚名网1 小时前
域名和服务器是什么?域名和服务器是什么关系?
服务器·前端
桃园码工1 小时前
4-Gin HTML 模板渲染 --[Gin 框架入门精讲与实战案例]
前端·html·gin·模板渲染
沈剑心1 小时前
如何在鸿蒙系统上实现「沉浸式」页面?
前端·harmonyos