开发者问题收集

Props 被传递为 null (未捕获 TypeError:无法读取未定义的属性(读取‘map’))

2023-11-07
101
import React, { useState, useEffect } from "react";
import { TaskLists } from "./TaskLists";
import { Daycard } from "./daycard";
import { getTasks, deleteTask } from "../api/task.api";

export function TaskManager() {
  const [tasks, setTasks] = useState([]);

  useEffect(() => {
    async function loadTasks() {
      const res = await getTasks();
      setTasks(res.data);
    }
    loadTasks();
  }, []);

  const removeTask = async (id) => {
    await deleteTask(id);
    setTasks(tasks.filter((task) => task.id !== id));
  };

  return (
    <div>
      <TaskLists tasks={tasks} removeTask={removeTask} />
      <Daycard tasks={tasks} removeTask={removeTask} />
    </div>
  );
}


import React from "react";
import { TaskCard } from "./TaskCard";

export function TaskLists({ tasks, removeTask }) {
  return (
    <div>
      {tasks.map((task) => (
        <TaskCard
          key={task.id}
          task={task}
          onDelete={() => removeTask(task.id)}
        />
      ))}
    </div>
  );
}

 import React from "react";
import { useNavigate } from "react-router-dom";
import { TaskCard } from "./TaskCard";
import { useState } from "react";

export function Daycard({ tasks, removeTask, hashv }) {
  let b = 0;
  const [hash, setHash] = useState(hashv);
  const navigate = useNavigate();

  const handleClick = () => {
    if (b === 0) {
      navigate(`/tasks-create?hash=${hash}`);
      console.log(`the hash is ${hash}`);
    }
  };

  return (
    <div
      onClick={handleClick}
      className="col pb-5 bg-light border border-dark flex-grow-1"
      style={{ height: "auto" }}
    >
      {tasks.map((task) => {
        if (task.hash === hash) {
          b = 1;
          return (
            <TaskCard
              key={task.id}
              task={task}
              onDelete={() => removeTask(task.id)}
            />
          );
        }
      })}
    </div>
  );
}

第一个是父组件,其他的是子组件,这就是我收到错误的原因:

TaskLists.jsx:7 Uncaught TypeError:无法读取未定义的属性(读取“map”) 在 TaskLists (TaskLists.jsx:7:14) 在 renderWithHooks (react-dom.development.js:16305:18)

我认为问题是因为在呈现这些子组件时,获取任务的初始 API 调用可能尚未完成。

2个回答

您必须为每个数据管理执行空异常处理程序。

我在下面添加了代码。

async function loadTasks() {
  const res = await getTasks();
  //console.log(res) and check your response here.
  setTasks(Array.isArray(res) ? res : [res]);    
     //res can be null, also res is not null but res.data can be null.
}
loadTasks();

此外,在 TaskLists 中,

export function TaskLists({ tasks = [], removeTask }) {
....

我希望我的回答能对您有所帮助

J.Porter
2023-11-07

当渲染组件时,您可以检查任务是否具有某些值。如果是,则渲染它,否则,则不渲染。

return (
    <div>
{tasks.length > 0 ?
      <>
      <TaskLists tasks={tasks} removeTask={removeTask} />
      <Daycard tasks={tasks} removeTask={removeTask} />
      </>
:null}
    </div>
  );
Ajaj Ali
2023-11-07