【问题标题】:Axios call mapping data from another table - ReactJsAxios 从另一个表调用映射数据 - ReactJs
【发布时间】: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);
      });
  }

【问题讨论】:

    标签: reactjs ajax axios


    【解决方案1】:

    这不是处理架构关系的客户端请求作业。

    要访问销售的客户和产品,您应该更改您的 api

    当您请求 Sales/GetSales 时,GetSales 应该遍历您的每一笔销售

    数据库和每个销售通过 customerId 在销售对象中查找相关客户和

    将其设置为结果。

    下面我们可以看到一个用nodejs和mongoose写的简单例子。

    // inside api
    
    const sales = await Sale.find({});
    sales.map((sale) => {
      sale.customer = await Customer.find({id: sale.customerId})
    });
    
    return sales.
    

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 2020-06-03
      • 1970-01-01
      相关资源
      最近更新 更多