【发布时间】:2021-02-10 22:08:08
【问题描述】:
我正在构建一个 React Web 应用程序,它对连接到数据库的表进行 CRUD 操作。我正在使用 axios 库从我的 api 控制器获取/发布请求,然后将数据映射到我的销售数组。 Sales 数组包含 Sales 表中的记录列表,该表与我的 Customer、Products 和 Store 表具有多对一的关系。获取结果仅显示客户、产品和商店的 ID 号,但我希望它获取客户、产品和商店对象并将它们存储在自己的数组中。 axios 调用只返回空对象。
我将如何解决这个问题?我是否需要进行 4 个 API 调用:第一个是从销售表中获取引用的 ID 列表并将每个 ID 传递给客户、产品和商店组件以获取数据?这是否需要将数组状态提升到 Sales 组件?
0:
customer: null
customerId: 1
dateSold: "2020-10-29T00:00:00"
id: 2
product: null
productId: 1
store: null
storeId: 1
__proto__: Object
1:
customer: null
customerId: 2
dateSold: "2020-10-27T00:00:00"
id: 3
product: null
productId: 3
store: null
storeId: 1
export class Sales extends Component {
constructor(props) {
super(props);
this.state = { sales: [], };
this.populateSalesData = this.populateSalesData.bind(this);
}
componentDidMount() {
this.populateSalesData();
}
populateSalesData = () => {
axios.get("Sales/GetSales")
.then((result) => {
this.setState({ sales: result.data })
console.log(result.data);
})
.catch((error) => {
console.log(error);
});
}
【问题讨论】: