【问题标题】:Rendering nested json response data in react UI在反应 UI 中呈现嵌套的 json 响应数据
【发布时间】:2021-12-10 14:24:46
【问题描述】:

这是正在获取的 json 的结构。我正在尝试通过 react 将一些嵌套线程数据呈现到网页。

import react, {useState, useEffect} from "react";
import axios from 'axios'
import ReactJson from 'react-json-view'

const FeaturedBoards = () => {
    const [boards, setBoards] = useState([{page: '', threads: {}}]); 

useEffect(() => {
    fetchBoards();
}, []);

const fetchBoards = () => {
    axios.get('https://a.4cdn.org/po/catalog.json')
    .then((res) => {
        console.log(res.data);
        setBoards(res.data);
    })
    .catch((err) => {
        console.log(err);
    });
};
    if(boards === 0) {
        return <div>Loading...</div>;
    }
    else{
    return (
        <div>
            <h1>Featured Boards</h1>
            <div className='item-container'>
                {boards.map((board) => (
                    <div className='board' key={board.id}>
                        <p>{board['threads']}</p>
                    </div>
                ))}
            </div>
        </div>
    );
    }
};

export default FeaturedBoards;

我已经尝试了所有方法来显示一些嵌套线程数据,但没有任何结果。我已经尝试过第二次调用 map on board 但没有运气,将它存储在一个变量中并从中调用仍然没有。我做错了什么吗?

【问题讨论】:

  • 既然你的 API 数据中的threads 属性看起来是数组,你为什么要用useState([{page: '', threads: {}}]) 将它初始化为一个对象呢?这就是导致错误的原因。另外,为什么首先使用单元素数组进行初始化?为什么不只是useState([])
  • 我的想法是你必须提供一个模板结构来填写。当我将 useState 切换到它时,它给了我这个错误。 Error: Objects are not valid as a React child (found: object with keys {no, sticky, closed, now, name, sub, com, filename, ext, w, h, tn_w, tn_h, tim, time, md5, fsize, resto, capcode, semantic_url, replies, images, omitted_posts, omitted_images, last_replies, last_modified}). If you meant to render a collection of children, use an array instead.
  • 至于你所说的尝试useState([]) 很难在这里重新发布整个代码,哈哈
  • const [boards, setBoards] = useState([]);
  • 每个 board threads 是一个对象数组(可能具有nostickyclosed 等属性)。 &lt;p&gt;{board['threads']}&lt;/p&gt; 对那个数据结构没有意义。正如错误消息所说,“对象(如 board.threads 中的对象)作为 React 子对象无效”

标签: reactjs react-native axios


【解决方案1】:

我相信How can I access and process nested objects, arrays or JSON?. 更全面地回答了这个问题,但要解释这个特定的数据结构,请继续阅读。


查看您的实际数据...boards 是一个数组。其中的每个元素都是一个具有page (int) 和threads (array) 属性的对象。每个threads 数组元素都是一个具有其他属性的对象。您可以使用map 来迭代数组并返回其中对象的 JSX 表示。

例如

const [boards, setBoards] = useState([]); // start with an empty array
const [loading, setLoading] = useState(true)

useEffect(() => {
  fetchBoards().then(() => setLoading(false))
}, []);

const fetchBoards = async () => {
  const { data } = await axios.get('https://a.4cdn.org/po/catalog.json')
  setBoards(data)
}

return loading ? <div>Loading...</div> : (
  <div>
    <h1>Featured Boards</h1>
    <div className="item-container">
      {boards.map(board => (
        <div className="board" key={board.page}> <!-- ? note "page", not "id" -->
          {board.threads.map(thread => (
            <p>{thread.name}</p>
            <p>{thread.sub}</p>
            <p>{thread.com}</p>
            <!-- etc -->
          ))}
        </div>
      ))}
    </div>
  </div>
)

【讨论】:

  • 成功了!谢谢,这就是我想要做的,将 key={} 从 id 更改为 page 有什么作用吗?
  • reactjs.org/docs/lists-and-keys.html#keys。您的 board 对象似乎没有 id 属性,因此您将每个 key 设置为 undefined 这将产生 "警告:列表中的每个孩子都应该有一个唯一的“键”道具。”
  • 啊,从我看到的错误中可以理解,我会检查一下,谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
  • 2019-10-08
  • 2021-09-28
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 2021-03-18
相关资源
最近更新 更多