繁体   English   中英

我收到一个错误:对象作为 React 子对象无效(找到:[object Promise])

[英]I got an Error: Objects are not valid as a React child (found: [object Promise])

我对 React 有点陌生。 我得到了这个错误:对象作为 React 子对象无效(找到:[object Promise])。 我不知道如何解决这个问题。 大家可以看看吗? 谢谢!

这是我的代码。

import React, { Component } from "react";
import "./App.css";

async function randomVerse() {
  const url = "https://labs.bible.org/api/?passage=random&type=json";
  const passage = await fetch(url);
  const passageJson = await passage.json();

  return passageJson;
}

const displayRandomVerse = async () => {
  let result = await randomVerse();
  let verse = "";
  verse += result[0].text;
  return verse;
};

const returnVerse = displayRandomVerse();

class App extends Component {
  constructor() {
    super();
    this.state = {
      verse: null
    };
  }

  componentDidMount() {
    this.setState({verse: returnVerse});
  };

  render() {
    return (
      <div className="App">
        <h1>Good Morning, XXX!</h1>
        <h3>Bible verse : {this.state.verse} </h3>
      </div>
    );
  }
}

export default App;

你必须在const returnVerse = await displayRandomVerse(); 中设置 await . 这应该给你价值

您需要在 componentDidMount 方法中获取并等待

async function randomVerse() {
      const url = "https://labs.bible.org/api/?passage=random&type=json";
      const passage = await fetch(url);
      const passageJson = await passage.json();
    
      return passageJson;
    }
    
    const displayRandomVerse = async () => {
      let result = await randomVerse();
      let verse = "";
      verse += result[0].text;
      return verse;
    };
    
    
    class App extends Component {
      constructor() {
        super();
        this.state = {
          verse: null
        };
      }
    
      async componentDidMount() {  //Notice changes in this section
        this.setState({verse: await displayRandomVerse()});
      };
    
      render() {
        return (
          <div className="App">
            <h1>Good Morning, XXX!</h1>
            <h3>Bible verse : {this.state.verse} </h3>
          </div>
        );
      }
    }
    
    export default App;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM