订单管理系统代码(前端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)
相关推荐
秦老师Q几秒前
「Chromeg谷歌浏览器/Edge浏览器」篡改猴Tempermongkey插件的安装与使用
前端·chrome·edge
滴水可藏海2 分钟前
Chrome离线安装包下载
前端·chrome
m512712 分钟前
LinuxC语言
java·服务器·前端
打鱼又晒网23 分钟前
【MySQL】数据库精细化讲解:内置函数知识穿透与深度学习解析
数据库·mysql
大白要努力!28 分钟前
android 使用SQLiteOpenHelper 如何优化数据库的性能
android·数据库·oracle
Myli_ing1 小时前
HTML的自动定义倒计时,这个配色存一下
前端·javascript·html
tatasix1 小时前
MySQL UPDATE语句执行链路解析
数据库·mysql
dr李四维1 小时前
iOS构建版本以及Hbuilder打iOS的ipa包全流程
前端·笔记·ios·产品运营·产品经理·xcode
南城花随雪。1 小时前
硬盘(HDD)与固态硬盘(SSD)详细解读
数据库
儿时可乖了1 小时前
使用 Java 操作 SQLite 数据库
java·数据库·sqlite