【问题标题】:Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead (React)错误:对象作为 React 子级无效(找到:[object Promise])。如果您打算渲染一组子项,请改用数组(React)
【发布时间】:2021-09-06 03:28:59
【问题描述】:

我想在我的 React 应用程序中显示这个“什么”,但我仍然遇到同样的错误。它实际上将其记录在控制台中,但在页面上总是出现相同的错误:

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead (React)

快速路线:

const express = require('express');
router = express.Router();

router.get("/", (req, res) => {
    res.send("What")
});

module.exports = router;

反应组件:

import React from 'react';

class Login extends React.Component {
    render() {
        function BackendRes() {
            const response = fetch("/login")
                                .then(res => res.text())
                                .then(text => console.log(text));
            return response;
        }
        return (
            <div>
                <BackendRes />
            </div>
        )
    }
}

export default Login;

【问题讨论】:

  • 您是否尝试在前端显示来自 express 的文本(What 是作为响应发送的文本 express api)?
  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: reactjs express components backend


【解决方案1】:

仅在初始渲染期间使用componentDidMount 生命周期方法调用api。然后设置state 以保持来自api的数据如下。然后使用statediv 中显示text

import React from "react";

class Login extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: "",
    };
    this.BackendRes = this.BackendRes.bind(this);
  }

  componentDidMount() {
    this.BackendRes();
  }

  BackendRes() {
    const response = fetch("/login")
      .then((res) => res.text())
      .then((text) => {
        this.setState({ data: text });
        console.log(text);
      });
  }

  render() {
    return <div>{this.state.data}</div>;
  }
}

export default Login;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2020-09-26
    • 2021-09-28
    • 2021-12-10
    相关资源
    最近更新 更多