接著我們開始要來整併前後端了
從前端React要去call 後端C#寫好的API
開啟cmd移動至此目錄下做React call api套件的npm下載(有package.json該層)
~\ClientApp
npm install axios
這裡更改一下ProductCard.js元件,將對應C#回傳的Model屬性名稱(可統一用小寫)改在React前端(接收端)
~\ClientApp\src\components\ProductCard.js
import React from 'react';
import { Link } from 'react-router-dom';
export default function ProductCard(props) {
return <div className="card product-card">
<div className="card-body">
<h5 className="card-title">{props.product.name}</h5>
<p className="card-text">{props.product.description}</p>
<Link to={`/product/${props.product.id}`}>View</Link>
</div>
</div>
}
呼叫端程式碼去引入Axios
進行ajax API呼叫
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import ProductCard from './ProductCard';
import Axios from 'axios';
export default class ProductList extends Component {
constructor(props) {
super(props);
this.state = {
products: []
};
}
async componentDidMount() {
//API 呼叫
let result = await Axios('https://localhost:7247/api/product');
this.setState({ 'products': result.data.products });
}
render() {
return (
<div className="row">
{this.state.products.map(product =>
<div key={product.id} className="col-4">
<ProductCard product={product} />
</div>
)}
</div>
);
}
}