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

React中useEffect内Promise返回数据传递给子组件为undefined问题求助

问题原因
  • 最直接的错误是你的Posts.js组件里多写了一行没有传post属性的<Post />调用:
<div className="posts">
  <Post /> {/* 这里没有传post参数,post值为undefined,子组件解构就会报错 */}
  {dataApi.map((post) => {
    return <Post post={post} key={uuidv4()} />;
  })}
</div>

组件首次渲染时,这行无参数的<Post />就会触发子组件里const { author, date_creation, message } = post的解构错误,因为此时post是undefined。

修复方案
  1. 首先删掉多余的无参数<Post />调用,修改Posts.js的返回部分:
return (
  <div className="posts">
    {dataApi.map((post) => {
      return <Post post={post} key={uuidv4()} />;
    })}
  </div>
);
  1. 可选优化:给Post组件加参数容错,避免后续传入异常值时直接报错:
// 给post设置默认空对象兜底
const Post = ({ post = {} }) => {
  const { author, date_creation, message } = post;
  return (
    <div className="post">
      <div className="post__author_group">
        <Avatar className={"post__avatar"} />
        <div className="post__author_and_date">
          <Author className="post__author" author={author ?? ''} />
          <Date className="post__date" date={date_creation ?? ''} />
        </div>
      </div>
      <Text message={message ?? ''} />
      {/* <Media /> */}
      <Interactions />
    </div>
  );
};
  1. 可选补充:给列表加加载状态、替换key值优化性能:
const Posts = () => {
  const [dataApi, setDataApi] = useState([]);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const toFetch = async () => {
      try {
        const response = await fetch("http://localhost:4200/api/post");
        const data = await response.json();
        console.log(data);
        setDataApi(data);
      } catch (err) {
        console.error('请求失败', err)
      } finally {
        setLoading(false)
      }
    };
    toFetch();
  }, []);

  if (loading) return <div>加载中...</div>

  return (
    <div className="posts">
      {dataApi.length === 0 ? <div>暂无帖子</div> : 
      // 用后端返回的唯一id做key,避免不必要的组件重渲染
      dataApi.map((post) => {
        return <Post post={post} key={post.id} />;
      })}
    </div>
  );
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:24:03