循环状态时无法读取未定义的属性(读取"长度")



大家好,我可以知道为什么状态是由api使用useEffect的值填充,不循环通过数据,只要我提供"?"在。map函数前或长度道具前标记?代码:1-定义状态:

const [userInProgressTasks, setUserInProgressTasks] = useState();

2-从api获取数据:

useEffect(() => {
let isMounted = true;
//to cancel our request if the component is unmounted
const controller = new AbortController();
const getUserTasksInProgress = async () => {
try {
const response = await axiosPrivate.get(
ApiConstants.GETALL_USER_IN_PROGRESS_TASKS_ENDPOINT(userObject?.id),
{
signal: controller.signal,
}
);
console.log(response?.data);
isMounted && setUserInProgressTasks(response?.data);
} catch (err) {
console.err(err);
//in case of error (exipre of refresh token) - send them back to login
navigate("/auth/login", {
state: { from: location },
replace: true,
});
}
getUserTasksInProgress();
//clean up function of useEffect - it runs when the component unmount
return () => {
isMounted = false;
//cancel any request when the component unmount
controller.abort();
};
}, []);
};

3-循环通过状态:

{userInProgressTasks?.length <= 0 ? (
<>
<div className="NoTasks-Image-Container">
<img src={InProgressImage} />
</div>
</>
) : (
<>
{userInProgressTasks?.map((t) => (
<p>{t.taskId}</p>
)  )}
</>
)}

知道为什么吗?这个标记有吗?'等待状态被填满或类似的东西?

生命周期如下:

  1. useState首先设置为未定义的userInProgressTasks
  2. useEffect

这就是为什么它要求你用?因为它们可能没有定义我建议总是初始化你的状态

const [userInProgressTasks, setUserInProgressTasks] = useState([]);

最新更新