You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中映射并将JSON结果以论坛帖子形式展示

在React中映射JSON数据并展示为论坛帖子样式

1. 优化数据获取逻辑

先修正你代码里的小问题:useState的更新是异步的,setPosts后立刻console.log(posts)拿不到最新值,应该打印response.data。另外建议增加加载和错误状态,避免初始posts为null时渲染报错:

import { useState, useEffect } from 'react';
import axios from 'axios';

function ForumPosts() {
  const [posts, setPosts] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchPosts = async () => {
      try {
        const response = await axios.get("http://hyeumine.com/forumGetPosts.php");
        setPosts(response.data);
        console.log(response.data); // 打印最新获取到的帖子数据
      } catch (err) {
        setError('加载帖子失败,请稍后重试');
        console.error(err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchPosts();
  }, [auth, refresher, userLogged]);

  // 处理加载、错误状态
  if (isLoading) return <div>加载中...</div>;
  if (error) return <div className="error">{error}</div>;

2. 映射JSON数据渲染论坛帖子

假设接口返回的每个帖子包含id、title、content、author、created_at这些字段,用map遍历数据,渲染成论坛风格的帖子卡片:

return (
    <div className="forum-posts-container">
      {posts.map(post => (
        <div key={post.id} className="forum-post-card">
          <div className="post-header">
            <h3 className="post-title">{post.title}</h3>
            <div className="post-meta">
              <span className="post-author">作者: {post.author}</span>
              <span className="post-date">{post.created_at}</span>
            </div>
          </div>
          <div className="post-content">
            {post.content}
          </div>
        </div>
      ))}
    </div>
  );
}

export default ForumPosts;

3. 添加论坛帖子样式

把下面的CSS代码放到组件对应的样式文件里,给帖子添加论坛风格的视觉效果:

.forum-posts-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.forum-post-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.post-header {
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.post-title {
  margin: 0 0 8px 0;
  font-size: 1.2rem;
  color: #2d3748;
}

.post-meta {
  font-size: 0.9rem;
  color: #718096;
  display: flex;
  gap: 16px;
}

.post-content {
  line-height: 1.6;
  color: #4a5568;
}

.error {
  color: #e53e3e;
  text-align: center;
  padding: 20px;
}

关键注意点

  • 给map返回的每个元素添加唯一key(这里用帖子id),避免React渲染警告
  • 初始状态将posts设为空数组[],比null更方便后续map操作
  • 处理加载、错误状态,提升用户体验

内容的提问来源于stack exchange,提问作者Jikk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:10:29