admin管理员组

文章数量:1202595

Problem I’m working on a React application for task management with a Kanban board. Each task has a comments array containing objects with text and timestamp fields, like this:

{
  id: "3",
  name: "Design landing page",
  description: "Create a visually appealing landing page for the new product.",
  status: "In Progress",
  priority: "Medium",
  comments: [
    { text: "Use the updated brand guidelines.", timestamp: "2025-03-01 14:00" }
  ],
  tags: ["Design", "UX"],
  assignedTo: "Bob Smith",
  createdAt: "2025-03-01 12:00"
}

However, when I try to render this data in a modal, I get the following error:

Uncaught Error: Objects are not valid as a React child (found: object with keys {text, timestamp}). If you meant to render a collection of children, use an array instead.

The app works fine if I remove the comments array from the task or leave it empty, but fails when there are comment objects. The error also occurs when adding a new comment through a form in the modal.

What I’ve Tried Validating the structure of the comments array using console.log. The logged data looks correct:

comments: [
  { text: "Use the updated brand guidelines.", timestamp: "2025-03-01 14:00" }
]

Relevant Code

TaskDetailsModal

const TaskDetailsModal = ({ task, onSave, onDelete }) => {
  const [editedTask, setEditedTask] = useState({
    ...task,
    comments: Array.isArray(taskments) ? taskments : [],
  });
  const [newComment, setNewComment] = useState("");

  const handleAddComment = () => {
    if (!newComment.trim()) return;
    const newCommentObject = {
      text: newComment.trim(),
      timestamp: new Date().toLocaleString(),
    };
    setEditedTask((prev) => ({
      ...prev,
      comments: [...prevments, newCommentObject],
    }));
    setNewComment("");
  };

  return (
    <div>
      <h2>Edit Task</h2>
      <div>
        {editedTaskments.map((comment, index) => {
          if (typeof comment === "object" && "text" in comment && "timestamp" in comment) {
            return (
              <div key={index}>
                <p>{comment.text}</p>
                <p>{comment.timestamp}</p>
              </div>
            );
          } else {
            console.error("Invalid comment format:", comment);
            return <p>Invalid comment format</p>;
          }
        })}
      </div>
      <input
        value={newComment}
        onChange={(e) => setNewComment(e.target.value)}
      />
      <button onClick={handleAddComment}>Add Comment</button>
    </div>
  );
};

ActiveSprint Component

const [tasks, setTasks] = useState([
  {
    id: "3",
    name: "Design landing page",
    description: "Create a visually appealing landing page.",
    comments: [
      { text: "Use the updated brand guidelines.", timestamp: "2025-03-01 14:00" },
    ],
  },
]);

Why is React throwing the "Objects are not valid as a React child" error when rendering the comments array, even though the data structure seems valid? How can I resolve this issue?

My assumption is I'm doing something wrong with the nested array encapsulation...

Problem I’m working on a React application for task management with a Kanban board. Each task has a comments array containing objects with text and timestamp fields, like this:

{
  id: "3",
  name: "Design landing page",
  description: "Create a visually appealing landing page for the new product.",
  status: "In Progress",
  priority: "Medium",
  comments: [
    { text: "Use the updated brand guidelines.", timestamp: "2025-03-01 14:00" }
  ],
  tags: ["Design", "UX"],
  assignedTo: "Bob Smith",
  createdAt: "2025-03-01 12:00"
}

However, when I try to render this data in a modal, I get the following error:

Uncaught Error: Objects are not valid as a React child (found: object with keys {text, timestamp}). If you meant to render a collection of children, use an array instead.

The app works fine if I remove the comments array from the task or leave it empty, but fails when there are comment objects. The error also occurs when adding a new comment through a form in the modal.

What I’ve Tried Validating the structure of the comments array using console.log. The logged data looks correct:

comments: [
  { text: "Use the updated brand guidelines.", timestamp: "2025-03-01 14:00" }
]

Relevant Code

TaskDetailsModal

const TaskDetailsModal = ({ task, onSave, onDelete }) => {
  const [editedTask, setEditedTask] = useState({
    ...task,
    comments: Array.isArray(task.comments) ? task.comments : [],
  });
  const [newComment, setNewComment] = useState("");

  const handleAddComment = () => {
    if (!newComment.trim()) return;
    const newCommentObject = {
      text: newComment.trim(),
      timestamp: new Date().toLocaleString(),
    };
    setEditedTask((prev) => ({
      ...prev,
      comments: [...prev.comments, newCommentObject],
    }));
    setNewComment("");
  };

  return (
    <div>
      <h2>Edit Task</h2>
      <div>
        {editedTask.comments.map((comment, index) => {
          if (typeof comment === "object" && "text" in comment && "timestamp" in comment) {
            return (
              <div key={index}>
                <p>{comment.text}</p>
                <p>{comment.timestamp}</p>
              </div>
            );
          } else {
            console.error("Invalid comment format:", comment);
            return <p>Invalid comment format</p>;
          }
        })}
      </div>
      <input
        value={newComment}
        onChange={(e) => setNewComment(e.target.value)}
      />
      <button onClick={handleAddComment}>Add Comment</button>
    </div>
  );
};

ActiveSprint Component

const [tasks, setTasks] = useState([
  {
    id: "3",
    name: "Design landing page",
    description: "Create a visually appealing landing page.",
    comments: [
      { text: "Use the updated brand guidelines.", timestamp: "2025-03-01 14:00" },
    ],
  },
]);

Why is React throwing the "Objects are not valid as a React child" error when rendering the comments array, even though the data structure seems valid? How can I resolve this issue?

My assumption is I'm doing something wrong with the nested array encapsulation...

Share Improve this question asked Jan 21 at 13:28 MalteMalte 3413 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

If the code above is correct, I feel you will need to wrap you're comment timestamp and text in a JSX tag.

   {editedTask.comments.map((comment, index) => {
      if (typeof comment === "object" && "text" in comment && "timestamp" in comment) {
        return (<div>{comment.text} {comment.timestamp} <div>);

At the minute you're returning two objects which isn't valid jsx

本文标签: