【问题标题】:Is there a way to pass a function to another function in the render return?有没有办法在渲染返回中将一个函数传递给另一个函数?
【发布时间】: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


【解决方案1】:

你没有从downloadJSON 返回任何东西,所以JSONToHTML 没有收到任何参数。要么将调用包装在 promise 中并返回 promise,要么将函数 asyncawait 作为 axios 调用,然后返回数据。无论哪种方式,您都必须从downloadJSON 的主体(return get.then(response =&gt; response)async 方法内部的return response.data)返回一些内容,以便JSONToHTML 接收参数。

【讨论】:

    【解决方案2】:

    感谢大家的回答。我在没有使用 async、await 或 Promise 的情况下解决了这个问题。罪魁祸首没有将 downloadJSON 函数包装在 componentDidMount 中。

    【讨论】:

      猜你喜欢
      • 2011-02-10
      • 1970-01-01
      • 2021-08-15
      • 2021-04-21
      • 2011-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多