无法将数据提取到 React.js 组件

Fetching data to a React.js component is not working

我有一个带有 React 组件的 quote.jsx 文件:

import React from 'react';
import fetch from 'node-fetch';
import './quotes.css';

export default class Quotes extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div className="quotes">
        {
          fetch('/random_quote')
            .then(res => res.json())
            .then(json => json.text())
        }
      </div>
    );
  }
}

如您所见,它使用 fetch 获取 JSON 对象,其中包含与引用相关的数据(引用文本和作者)并显示一些此类数据。

当我使用 webpack 捆绑我的系统时,我收到此警告消息:

WARNING in ./fe/~/encoding/lib/iconv-loader.js 9:12-34 Critical dependency: the request of a dependency is an expression

当我 运行 我的网络系统访问 URL 谁应该显示这个组件时,我得到以下错误:

Uncaught 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 or wrap the object using createFragment(object) from the React add-ons. Check the render method of Quotes.

我的后端没有错误,JSON 正在正确生成和返回。这不是问题。

我对 React.js 比较陌生,之前从未见过此消息。

有人可以帮我解决这个问题吗?我整个星期天都在与这个错误作斗争,没有更多的选择来处理它。

不要在 render 中执行 fetch,而是在 componentDidMountcomponentWillMount 中执行。

以下是我的实现方式:

import React from 'react';
import fetch from 'node-fetch';
import './quotes.css';

export default class Quotes extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    fetch('/random_quote')
    .then(res => res.json())
    .then(json => {
      this.setState({text: json.text()});
    });
  }

  render() {
    return(
      <div className="quotes">
        {this.state.text}
      </div>
    );
  }
}