簡體   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