【发布时间】:2021-06-10 23:34:39
【问题描述】:
我正在尝试将一个函数传递给另一个函数。
第一个函数下载一些 JSON 数据然后返回它(这个工作)。下一个函数应该将 JSON 数据映射到 HTML 代码(这不起作用)。
我已将第一个函数调用嵌套在第二个函数中,但在我的浏览器和 React 中没有结果“无法读取未定义的属性 'map'。”但是不应该定义映射,因为首先评估内部函数吗?
import React from 'react';
import axios, { post, get } from 'axios';
class Line {
constructor(json) {
this.id = json.id
this.name = json.name
this.html = <p>{this.name}'s ID is {this.id}.</p>
}
}
class Viewer extends React.Component {
constructor(props) {
super(props);
}
downloadJSON() {
const url = 'http://127.0.0.1:5000/sample_data';
console.log("Downloaded the JSON File from the Server")
get(url)
.then(
(res) => { return res }
)
}
JSONToHTML(jsondata) {
return jsondata.map(item => Line)
}
render() {
return (
<div>
<p>{this.JSONToHTML(this.downloadJSON()).html}</p>
<p>OK</p>
</div>
)
}
}
export default Viewer
【问题讨论】:
-
JSONToHTML接受来自downloadJSON的承诺,因此您需要重构以使用await或在回调中使用.then。 -
确实定义了 map ,但是 jsondata 是未定义的(这就是错误的意思),因为您从无处传递它。我会在downloadJSON中添加另一个然后在那里做地图。
标签: javascript html reactjs next.js