iT邦幫忙

2022 iThome 鐵人賽

DAY 25
0
Software Development

.NET Core與React組合開發技系列 第 25

.NET Core與React組合開發技_第25天_重構加入至購物車的程式

  • 分享至 

  • xImage
  •  

~/src/components/Products/AddToCart.js

import React, { Component } from 'react';
import Axios from 'axios';

export default class AddToCart extends Component {

    constructor(props) {
        super(props);

        this.onSubmit = this.onSubmit.bind(this);
    }

    async onSubmit(e) {
        e.preventDefault();
        let sessionId = localStorage.sessionId;
        let result = await Axios.post('/api/cart', { productId: this.props.productId, sessionId: sessionId });
        localStorage.sessionId = result.data.sessionId;
    }

    render() {
        return <form onSubmit={this.onSubmit}>
            <div className="form-row">
                <div className="form-group">
                    <button className="btn btn-primary form-control" type="submit">
                        Add to Cart
                    </button>
                </div>
            </div>
        </form>;
    }

}

在後端C#專案新增一個Model
存放ProductID

public class AddItemCommand
{
    public int ProductId { get; set; }
}

新增CartService(要來將DB存取業務一樣從Action抽離降低耦合)

public class CartService
{
    private readonly StoreContext dbContext;

    public CartService(StoreContext dbContext)
    {
        this.dbContext = dbContext;
    }

    public void AddItem(AddItemCommand command)
    {
        var cart = new ShoppingCart { SessionId = Guid.NewGuid(), CreatedOn = DateTime.Now };
        cart.Items.Add(new CartLineItem { ProductId = command.ProductId, Quantity = 1 });

        dbContext.ShoppingCart.Add(cart);
        dbContext.SaveChanges();
    }
}

Program.cs起初服務註冊也要記得補配置

services.AddScoped<CartService>();

編輯修改CartController

[Route("api/[controller]")]
[ApiController]
public class CartController : ControllerBase
{
    private readonly StoreContext dbContext;
    private readonly CartService cartService;
    public CartController(CartService cartService)
    {
        this.cartService = cartService;
    }

    [HttpPost]
    public IActionResult AddItem(AddItemCommand command)
    {
        cartService.AddItem(command);
        return Ok();
    }
}

public class AddItemCommand
{
    public int ProductId { get; set; }
}


上一篇
.NET Core與React組合開發技_第24天_將商品添加到購物車API
下一篇
.NET Core與React組合開發技_第26天_C#單元測試介紹與常用框架
系列文
.NET Core與React組合開發技30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言