【问题标题】:How do I return an object array in an express function so that it can be rendered or displayed on the frontend?如何在 express 函数中返回对象数组,以便可以在前端呈现或显示它?
【发布时间】:2021-06-13 02:01:05
【问题描述】:
//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>
        )
   
    }
}

【问题讨论】:

  • 道歉@ArunKumarMohan 问题是网页正文中没有显示任何内容,我认为它会显示导出的 storeInput 函数的返回结果并且没有错误。

标签: javascript mongodb express axios mern


【解决方案1】:

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

search.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);
    });
}

【讨论】:

  • 抱歉,我正在更新我的代码,不小心粘贴不正确导致重复。我已尝试实现您的代码,并且它与您拥有的回调一起使用,但我不确定如何使用它来让品牌名称、卡路里等的值适应我的查询结果作为当前输出的后端是硬编码的。我更改了代码以尝试使用您给我的内容,但我很确定我的方法完全错误。我已经更新了对主要问题的更改。
  • 好的,我已经相应地更新了答案。请查看“search.js”部分
  • 谢谢。它现在确实显示了结果数组,如果我要根据用户输入获取输入,那么 storeInput("Lays", callback); 中的 "Lays" 会显示出来。在 componentDidMount 中,可以简单地替换为一个名为“input”的变量。然后我会以某种方式将接收到的输入从用户发送到 componentDidMount() 函数?
  • 所以基本上,您可以创建另一个方法来监听您的输入值并执行与“componentDidMount”中相同的功能。我建议将其变得普遍。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
相关资源
最近更新 更多