首页 > 解决方案 > 如何在 express 函数中返回对象数组,以便可以在前端呈现或显示它?

问题描述

//search.js file

import axios from "axios";

export function storeInput(input, callback) {

  //input = document.getElementById("a").value;
  let result = [];

  console.log(input);   

  if (!callback) return;
  
  axios.post("http://localhost:4000/id", {
    searchWord: input,
  }).then((response) => {
    result = response.data;
    console.log(result);
  });

  callback([
    {
      result
    }
  ]);


}

这是一个搜索功能,它转到后端并检索数据,它可以正常工作,因为控制台显示了应该返回的数组,如下所示。有人告诉我,下面的对象无法直接渲染,因此我尝试通过在线遵循一些指南使对象“可读”,但没有成功。

[{…}]
0:
brand_name: "Lays"
calories: 160
calories_fat: 90
first_ingredient: "other"
processed: "yes"
product: "Classic potato chips"
saturated_fat: 2
serving_size: 28
short_name: "potato chips"
sodium: 170
sugar: 1
trans_fat: 0
_id: "60207f84a8241d2bb803423b"
__proto__: Object
length: 1
__proto__: Array(0)

这是试图使对象可渲染并将其显示在网页上的前端页面。

//snack-search.components.js file

import React, { Component } from 'react';
import {storeInput} from "./search.js";

const Snacks = props => (
    <tr>
        
        <td>{props.snacks.brand_name}</td>
        <td>{props.snacks.product}</td>
        <td>{props.snacks.short_name}</td>
        <td>{props.snacks.serving_size}</td>
        <td>{props.snacks.calories}</td>
        <td>{props.snacks.calories_fat}</td>
        <td>{props.snacks.saturated_fat}</td>
        <td>{props.snacks.trans_fat}</td>
        <td>{props.snacks.sodium}</td>
        <td>{props.snacks.sugar}</td>
        <td>{props.snacks.first_ingredient}</td>
        <td>{props.snacks.processed}</td>

    </tr>
)

export default class SnackSearch extends Component {
    constructor(props) {
        super(props);
            this.state = { snacks: null };
    }
    
    setSnackState(snacks = null) {
        this.setState({ snacks });
    }
    
    componentDidMount() {
        // make async call here not in render
        const callback = (snacks) => this.setSnackState(snacks);
        storeInput("Lays", callback);
    }

    SnackList() {
        const snacksList = this.state.snacks;
        return (
          snacksList &&
          snacksList.map((currentSnack, i) => (
            <Snacks snacks={currentSnack} key={i} />
          ))
        );
    }

    render() {

        return (
            <div className = "search">
                <table> {this.SnackList()}</table>
            </div>
        )
   
    }
}

标签: javascriptmongodbexpressaxiosmern

解决方案


好的,所以对于异步承诺,在承诺解析中使用回调。请看一看

搜索.js

/**
 *
 * @param {String} input
 * @param {Function} callback
 */
export function storeInput(input, callback) {
    let result = [];

    if (!callback) return;

    axios.post("http://localhost:4000/id", {
        searchWord: input,
    }).then((response) => {
        result = response.data;
        // if result is of array type you are expecting
        callback(result);
    });
}


推荐阅读