赞
踩
前端:
App.jsx
- 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
- 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
- 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
- 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
- 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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。