【问题标题】:Get data from Node endpoint and pass into React frontend从 Node 端点获取数据并传递到 React 前端
【发布时间】:2018-02-07 15:24:06
【问题描述】:

我正在访问来自本地节点服务器的 get 请求,并将数据接收回 React 代码,但我不知道如何使用接收到的数据。使用 React 和 Node 的完整初学者。

const https = require("https");
const url =
"http://localhost:9001/products";
 https.get(url, res => {
    res.setEncoding("utf8");
    let body = ""
    res.on("data", data => {
        body += data;
    });
    res.on("end", () => {
      console.log(
          body
      );
    });
});

控制台显示所有正在返回的数据,但现在我想使用该数据,将其传递给要导出的成本

export default data;

每当我尝试在 cont url 代码之外提醒正文时,它都会显示未定义。如何抓取要导出的数据?

【问题讨论】:

  • 能否请您描述一下您希望使用数据的方式?我想说,在您的示例数据中,存储在 body 变量中,仅在回调范围内。因此,您的应用程序看不到这些数据。当然,最好在 redux 状态下保存响应。
  • 您无法导出仅在运行时创建的任何内容。导出告诉您的模块捆绑器在哪里可以找到它从其他模块中使用的代码。您不能用它“传输”运行时信息。可能这个请求属于某种<Product> 组件生命周期方法。但我无法准确判断,因为您没有发布任何反应代码。你做过 react/redux 教程吗?
  • 我目前有一个 data 文件夹,其中包含一个 producst.js 文件和硬编码的产品 json 和一个名为 data 的 const 已导出。我想改为从节点服务器中提取数据

标签: javascript node.js reactjs get


【解决方案1】:

Container Component 的完美用例:

您应该在 Parent/Container 组件中进行 api 调用,然后将响应数据存储在 state 中。然后,您可以将数据作为道具传递给任何孩子:

const https = require("https");

export default class FetchData extends Component {

    constructor () {
        super();

        this.state = {
            data: null
        };
    }

    componentDidMount() {
        this.fetchData();
    }

    fetchData = () => {
        const url = "http://localhost:9001/products";
        https.get(url, res => {
            res.setEncoding("utf8");
            let body = ""
            res.on("data", data => {
                body += data;
            });
            res.on("end", () => {
                // Store data to state
                this.setState({
                    data: body
                });
            });
        });
    };

    render() {
        return (
            <div>
                <Child1 data={this.state.data} />
                <Child2 data={this.state.data} />
                <Child3 data={this.state.data} />
            </div>
        )
    }
}

【讨论】:

    猜你喜欢
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多