在React UI中渲染嵌套JSON响应数据的问题咨询
问题排查
- 加载状态判断逻辑错误:
boards为数组类型,永远不可能等于数字0,你的加载逻辑永远不会触发,页面初始就会直接渲染初始空结构 - 直接将
threads数组对象作为文本渲染,React不支持直接渲染引用类型数据,因此没有可见内容输出 - 遍历
boards时绑定的key={board.id}不存在,接口返回的页面对象只有page字段没有id字段,会触发React的key警告 - 额外小问题:导入React时首字母需要大写,否则会触发React识别错误
修正后可运行代码
import React, {useState, useEffect} from "react"; import axios from 'axios' const FeaturedBoards = () => { // 初始状态设为空数组更合理 const [boards, setBoards] = useState([]); useEffect(() => { fetchBoards(); }, []); const fetchBoards = () => { axios.get('https://a.4cdn.org/po/catalog.json') .then((res) => { setBoards(res.data); }) .catch((err) => { console.log(err); }); }; // 修正加载判断:数组长度为0时显示加载状态 if(boards.length === 0) { return <div>Loading...</div>; } return ( <div> <h1>Featured Boards</h1> <div className='item-container'> {/* 用唯一的page字段作为key */} {boards.map((board) => ( <div className='board' key={board.page}> <h3>第{board.page}页</h3> <div className='thread-list'> {/* 嵌套遍历threads数组,取具体字段渲染 */} {board.threads.map(thread => ( <div className='thread-item' key={thread.no}> <h4>{thread.sub || '无标题'}</h4> <p dangerouslySetInnerHTML={{__html: thread.com || '无内容'}}></p> </div> ))} </div> </div> ))} </div> </div> ); }; export default FeaturedBoards;
注:接口返回的
com字段是带HTML标签的内容,所以用dangerouslySetInnerHTML渲染可以保留原格式,不需要的话直接写{thread.com || '无内容'}即可。
内容的提问来源于stack exchange,提问作者meanthatmuchtoyou
相关产品推荐
相关产品推荐

