繁体   English   中英

使用 reactjs 渲染 JSON 数据(来自 reddit API)

[英]Render JSON data (from reddit API) with reactjs

React 非常新,所以我可能会以错误的方式处理这个问题......我希望我的应用程序从文本输入字段获取输入,从 reddit API 检索 JSON(url 是根据文本输入构建的),然后呈现来自 JSON 的数据,循环遍历每个条目。 我正在使用 useState 来触发数据渲染。 我可以成功检索数据并输出特定值,但我希望能够有一个循环将数据动态输出到各种 HTML 元素中。

到目前为止,这是我允许我输出一些特定值作为示例的内容:

import React, { useState } from 'react';

const App = () => {
  const [retrievedData, setRetrievedData] = useState([])
  
  const runSearch = async() => {
    const searchInput = document.getElementById('searchInput').value
    const searchUrl = 'https://www.reddit.com/r/' + searchInput + '/new/.json?limit=5'
    const response = await fetch(searchUrl)
    const redditResponse = await response.json()

    setRetrievedData(<>
    <p>{JSON.stringify(redditResponse.data.children[0].data.author)}</p>
    <p>{JSON.stringify(redditResponse.data.children[0].data.title)}</p>
    </>)
  }

  return (
    <>
      <section>
        <input type="text" id='searchInput' placeholder='Enter a subreddit...'></input>
        <button onClick={runSearch}>
          Get Data
        </button>
        <div>{retrievedData}</div>
      </section>
    </>
  );
};

export default App;

这是从 reddit API 中检索到的 JSON 示例,仅使用我在上面的代码中使用的示例值进行精简:

{
  "kind": "Listing",
  "data": {
    "modhash": "",
    "dist": 5,
    "children": [
      {
        "kind": "t3",
        "data": {
          "author": "author1",
          "title": "title1"
        }
      },
      {
        "kind": "t3",
        "data": {
          "author": "author2",
          "title": "title2"
        }
      },
      {
        "kind": "t3",
        "data": {
          "author": "author3",
          "title": "title3"
        }
      },
      {
        "kind": "t3",
        "data": {
          "author": "author4",
          "title": "title4"
        }
      },
      {
        "kind": "t3",
        "data": {
          "author": "author5",
          "title": "title5"
        }
      }
    ],
    "after": "t3_jnu0ik",
    "before": null
  }
}

我只需要最终渲染的输出是这样的:

<h2>TITLE 1</h2>
<h4>AUTHOR 1</h4>
<p>SELFTEXT 1</p>

...并为检索到的每个帖子数据重复。

我见过各种不同的方式来呈现 JSON 数据,其中许多显示循环和/或 .map() 方法,但我似乎无法让它们工作,并且想知道这是否是一个问题使用状态。 也许我应该以其他方式呈现数据?

不需要设置jsx到state,直接用map迭代子数据即可

尝试这个

const App = () => {
  const [retrievedData, setRetrievedData] = useState([])
  
  const runSearch = async() => {
    const searchInput = document.getElementById('searchInput').value
    const searchUrl = 'https://www.reddit.com/r/' + searchInput + '/new/.json?limit=5'
    const response = await fetch(searchUrl)
    const redditResponse = await response.json()
    if (redditResponse.data.children && redditResponse.data.children.length) {
      setRetrievedData(redditResponse.data.children)
    }
  }

  return (
    <>
      <section>
        <input type="text" id='searchInput' placeholder='Enter a subreddit...'></input>
        <button onClick={runSearch}>
          Get Data
        </button>
        <div>
          {
            retrievedData.map((children, index) => {
              return (
                <div key={children.data.author + index}>
                  <div>Kind: { children.kind }</div>
                  <div>Author: { children.data.author }</div>
                  <div>Title: { children.data.title }</div>
                </div>
              )
            })
          }
        </div>
      </section>
    </>
  );
};

暂无
暂无

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

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