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

我的React自定义Hook存在什么问题?

问题分析与解决方案

Hey there! I see the issue with your code—it's a small but tricky detail in how your custom hook returns data. Let's break it down:

The Root Problem

In your useComments hook, you're returning [Comments] (an array containing your posts array). That means when you call const Comments = useComments() in App.js, you're actually getting a 2-dimensional array ([[post1, post2, ...]]) instead of the flat array of posts you expect.

When you try to map over this nested array, each "comment" in the loop is actually the entire posts array itself—not an individual post object. Since arrays don't have a title property, your list items end up empty, and there's no console error because accessing undefined.title in React just renders nothing silently.

Fixing the Code

Let's adjust the return value in your custom hook first:

Modified useComments.js

import {useState, useEffect} from "react";

const useComments = () => {
  const [comments, setComments] = useState([]); // 小细节:变量名改成小写开头更符合JS规范
  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts", {
      "mode": "cors",
      "credentials": "omit"
    })
    .then(res => res.json())
    .then(data => setComments(data))
  }, []);
  
  // 直接返回状态数组,不用包裹在另一个数组里
  return comments;
};

export default useComments;

Then, we can clean up the variable naming in App.js (optional but recommended for consistency):

Modified App.js

import React from "react";
import useComments from "./hooks/useComments"

const App = () => {
  const comments = useComments(); // 小写开头,区分组件和普通状态变量
  const renderedItems = comments.map((comment) => {
    return <li key={comment.id}>{comment.title}</li>;
  });
  return (
    <div>
      <h1>Comments</h1>
      <ul>{renderedItems}</ul>
    </div>
  );
}

export default App;

Why This Works

Custom hooks can return any value—you don't need to mimic the array return style of useState unless you're returning multiple values (like a state setter alongside the state). In this case, you only need to return the array of posts directly, so your component gets the flat array it needs to map over correctly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 03:57:32