javascript - 如何在 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>
)
}
}
解决方案
好的,所以对于异步承诺,在承诺解析中使用回调。请看一看
搜索.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);
});
}
推荐阅读
- php - 当有人移动到根文件夹 opencart 时,子文件夹 opencart 会话丢失
- django - 带有 SuccessMessageMixin 错误的 django CreateView:没有属性“cleaned_data”
- javascript - 可见性隐藏 DOM 是否监听 JS 事件?
- docker - Meteor 1.6.1.1 - 搜索所见即所得
- python-3.x - 从具有给定数据结构的二进制文件中读取
- python - 分区未分配给 Kafka 消费者实例
- html - 嵌套循环如何与玉一起使用?
- java - 加载批处理 XML 配置时未找到 Spring bean,但在应用程序上下文中可用
- php - 这个 zend 控制器和动作如何协同工作?
- twitter-bootstrap - 将 Bootstrap 3 网格应用于特殊的屏幕尺寸