【问题标题】:How to display data from json in React如何在 React 中显示来自 json 的数据
【发布时间】:2021-10-26 11:38:48
【问题描述】:

我尝试创建生成随机报价的简单应用程序。 我创建了一个函数(我认为)从 json 文件中获取我想要的数据。但是当我尝试将该函数传递给我的 App 函数时,我得到错误:对象作为 React 子对象无效(找到:[object Promise])

功能引用:

function Quote (data) {
  var x = (Math.floor(Math.random() * (103 - 1) + 1) );
  return fetch('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json')
  .then((response) => response.json())
  .then((responseJson) => {

    console.log(responseJson['quotes'][0]['author']);
    return responseJson['quotes'][x]['author'];
  })


  
  .catch((error) => {
    console.error(error);
  });
}

应用功能:

function App() {
  var text = '';
  return (
    
    <div id="quote-box">
      <div id="author"><Quote /></div>
      <button id="new-quote">New Quote</button>
      <a href="twitter.com" id="tweet-quote">Tweet</a>
    </div>
  );
}

【问题讨论】:

  • 您的Quote 不是React 组件。这是一个返回承诺的函数。我认为您需要阅读文档here 以更好地了解 React 组件的工作原理。

标签: javascript reactjs json


【解决方案1】:

我会在开始时使用 useEffect 来触发调用。并使用 useState 保存该值。然后在onClick上也加入同样的逻辑。

import { useEffect, useState } from "react";

function getQuote() {
  var x = Math.floor(Math.random() * (103 - 1) + 1);
  return fetch(
    "https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json"
  )
    .then((response) => response.json())
    .then((responseJson) => {
      console.log(responseJson["quotes"][0]["author"]);
      return responseJson["quotes"][x]["author"];
    })

    .catch((error) => {
      console.error(error);
    });
}

export default function App() {
  const [author, setAuthor] = useState("");

  useEffect(() => {
    getQuote().then((newAuthor) => setAuthor(newAuthor));
  }, []);
  return (
    <div id="quote-box">
      <div id="author">{author}</div>
      <button
        id="new-quote"
        onClick={() => getQuote().then((newAuthor) => setAuthor(newAuthor))}
      >
        New Quote
      </button>
      <a href="twitter.com" id="tweet-quote">
        Tweet
      </a>
    </div>
  )
}

【讨论】:

  • 天哪,它有效 ^^ 非常感谢你,我尝试了大约 10 个小时
【解决方案2】:

您也可以通过这种方式存档。创建一个自定义钩子并使用它。

import React from "react";

function useFetchQuote(newQuote) {
  const [author, setAuthor] = React.useState();

  React.useEffect(() => {
    var x = Math.floor(Math.random() * (20 - 1) + 1);
    return fetch(
      "https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json"
    )
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson["quotes"][x]["author"]);
        setAuthor(responseJson["quotes"][x]["author"]);
      })
      .catch((error) => {
        console.error(error);
      });
  }, [newQuote]);

  return { author };
}

function App() {
  const [newQuote, setQuote] = React.useState(0);
  const { author } = useFetchQuote(newQuote);

  return (
    <div id="quote-box">
      <div id="author">{author}</div>
      <button id="new-quote" onClick={() => setQuote(newQuote + 1)}>
        New Quote
      </button>
      <a href="twitter.com" id="tweet-quote">
        Tweet
      </a>
    </div>
  );
}

export default App;

【讨论】:

    【解决方案3】:

    React 组件中返回承诺不会像您在代码中所做的那样工作。 React 组件必须返回 jsx。例如在一个名为Quote.js的文件中

    import * as React from 'react';
    
    const url =
      'https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json';
    
    const Qoute = () => {
      const [quote, setQuote] = React.useState(null);
    
      React.useEffect(() => {
        fetch(url)
          .then((response) => response.json())
          .then((data) => {
            const randomNumber = 1; // Generate random number which is lesser or equal to data's length
            setQuote(data['quotes'][randomNumber]);
          });
      }, []);
    
      if (!quote) return <React.Fragment>Loading...</React.Fragment>;
    
      return <div>{JSON.stringify(quote)}</div>;
    };
    
    export default Qoute;
    

    然后你只需要将它导入到你想使用它的地方并像这样调用它

    <Quote />
    

    PS:我是从typescript 转换过来的,如果出现问题,我很乐意提供帮助。请记住更新我发表评论的。祝你好运,兄弟。

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 2021-01-20
      • 2022-01-21
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      相关资源
      最近更新 更多