12.11 오류 관련
강의 19:07까지 따라하다가 오류가 갑자기 많이 뜨는데 어디에서 잘못된 것인지 모르겠습니다..

.
DiaryList.jsx
import "./DiaryList.css";
import Button from "./Button";
import DiaryItem from "./DiaryItem";
const DiaryList=({data})=>{
return <div className="DiaryList">
<div className="menu_bar">
<select>
<option value={"latest"}>Newest</option>
<option value={"oldest"}>Oldest</option>
</select>
<Button text={"write new diary"} type={"POSITIVE"} />
</div>
<div className="list_wrapper">
{data.map((item)=><DiaryItem key={item.id} {...item}/>)}
</div>
</div>;
};
export default DiaryList;DiaryItem.jsx
import {getEmotionImage} from "../util/get-emotion-image";
import Button from "./Button";
import "./DiaryItem.css";
const DiaryItem=({id,emotionId,createdDate,content})=>{
return (<div className="DiaryItem">
<div className={`img_section img_section_${emotionId}`}>
<img src={getEmotionImage(emotionId)}/>
</div>
<div className="info_section">
<div className="created_date">
{new Date(createdDate).toLocaleDateString()};
</div>
<div className="content">{content}</div>
</div>
<div className="button_section">
<Button text={"수정하기"} />
</div>
</div>
);
};
export default DiaryItem;App.jsx
import './App.css'
import{useReducer,useRef,createContext} from "react";
import {Routes,Route} from "react-router-dom";
import Home from "./pages/Home";
import Diary from "./pages/Diary";
import New from "./pages/New";
import Edit from "./pages/Edit";
import Notfound from "./pages/Notfound";
const mockData=[
{
id:1,
createdDate:new Date("2025-02-18").getTime(),
emotionId:1,
content:"1번 일기 내용",
},
{
id:2,
createdDate:new Date("2025-02-17").getTime(),
emotionId:2,
content:"2번 일기 내용",
},
{
id:3,
createdDate:new Date("2025-01-15").getTime(),
emotionId:3,
content:"3번 일기 내용",
},
];
function reducer(state,action){
switch(action.type){
case "CREATE": return [action.data,...state];
case "UPDATE": return state.map((item)=>
String(item.id)===String(action.data.id)
?action.data
: item
);
case "DELETE":
return state.filter(
(item)=>String(item.id)!==String(action.id)
);
default:
return state;
}
}
export const DiaryStateContext=createContext();
export const DiaryDispatchContext=createContext();
function App() {
const [data,dispatch]=useReducer(reducer,mockData);
const idRef=useRef(3);
//새로운 일기 추가
const onCreate=(createdDate,emotionId,content)=>{
dispatch({
type:"CREATE",
data:{
id: idRef.current++,
createdDate,
emotionId,
content,
},
});
};
//기존 일기 수정
const onUpdate =(id,createdDate,emotionId,content)=>{
dispatch({
type:"UPDATE",
data: {
id,
createdDate,
emotionId,
content,
},
});
};
//기존 일기 삭제
const onDelete=(id)=>{
dispatch({
type:"DELETE",
id,
});
};
return (
<>
<DiaryStateContext.Provider value={data}>
<DiaryDispatchContext.Provider value={{
onCreate,
onUpdate,
onDelete,
}}
>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/new" element={<New />} />
<Route path="/diary/:id" element={<Diary />} />
<Route path="/edit/:id" element={<Edit />} />
<Route path="*" element={<Notfound />} />
</Routes>
</DiaryDispatchContext.Provider>
</DiaryStateContext.Provider>
</>
);
}
export default App
답변 2
0
안녕하세요 진성원님 이정환입니다.
문제의 원인은 Home 컴포넌트에 있는걸로 보입니다. 그런데 해당 코드 첨부가 되어 있지 않아 확인이 어렵네요 ㅠㅠ
질문 가이드라인을 꼭 확인하시어 전체 프로젝트 코드를 깃허브 또는 구글 드라이브 링크로 보내주셔야 정확한 원인을 살펴볼 수 있으니 참고해주세요!
0
Home.jsx 입니다!
import { useState,useContext } from "react";
import { DiaryStateContext } from "../App";
import Header from "../components/Header";
import Button from "../components/Button";
import DiaryList from "../components/DiaryList";
const getMonthlyData=(pivotDate,data)=>{
const beginTime=new Date(pivotDate.getFullYear(),
pivotDate.getMonth(),
1,0,0,0
).getTime();
const endTime=new Date(
pivotDate.getFullYear(),
pivotDate.getMonth()+1,
0,
23,
59,
59
).getTime();
return data.filter((item)=>beginTime<=item.createdDate&&item.createdDate<=endTime
);
}
const Home=()=>{
const data=useContext(DiaryStateContext);
const [pivotDate,setPivotDate]=useState(new Date());
const monthlyData=getMonthlyData(pivotDate,data);
const onIncreaseMonth=()=>{
setPivotDate(
new Date(pivotDate.getFullYear(),pivotDate.getMonth()+1)
);
};
const onDecreaseMonth=()=>{
setPivotDate(
new Date(pivotDate.getFullYear(),pivotDate.getMonth()-1)
);
};
return (<div>
<Header
title={`${pivotDate.getFullYear()}년 ${
pivotDate.getMonth()+1
}월`}
leftChild={<Button onClick={onDecreaseMonth} text={"<"} />}
rightChild={<Button onClick={onIncreaseMonth} text={">"} />}
/>
<DiaryList data={monthlyData}/>
</div>
);
};
export default Home;
0
map 메서드의 문제보다는 ToodList 컴포넌트에서 Props로 전달받은 data가 현재 undefiend이라 문제가 발생하는 것 같습니다.
전체 프로젝트를 제가 가동해봐야 문제 확인이 가능할 것 같습니다. 누차 말씀드린대로 전체 프로젝트 코드를 깃허브나 구글드라이브 링크로 보내주실 수 있을까요?
0

안녕하세요 코드 받아서 확인해봤는데 동일한 문제가 재현되지 않고 있어요 ㅠㅠ 혹시 어떤 상황에 오류가 발생하는지 알려주실 수 있을까요? (콘솔에도 오류 메세지는 출력되지 않습니다)
0
음 .. 이상하네요 혹시 프로젝트를 가동 중단 하신 다음 아예 새롭게 다시 가동해보시겠어요? 보내주신 코드에는 아무런 문제가 없는걸로 확인됩니다.
PS. 브라우저는 엣지가 아닌 크롬을 권장합니다
0
안녕하세요, 인프런 AI 인턴입니다. 진성원님, 리액트 프로젝트에서 map 메서드를 사용하면서 오류가 발생한 부분을 말씀드리겠습니다. data가 정의되지 않아 map 메서드를 호출할 수 없는 것이 주된 이유일 수 있습니다. 다음의 해결책을 고려해보세요.
data가 제대로 전달되었는지 확인:DiaryList컴포넌트가data를props로 받아야 하며,App컴포넌트에서data를 올바르게 전달하는지 확인이 필요합니다.App이Home컴포넌트에DiaryList를 렌더링하면서data를 전달했는지 확인하세요.data가 배열인지 확인:data가 배열이 아니라면map을 호출할 수 없습니다.console.log를 사용하여data의 타입을 확인하고, 배열인지 확인해 보세요.오타 확인:
DiaryList컴포넌트에서item객체의 속성을 사용할 때 잘못된 키를 사용하지 않았는지 확인하세요.
다음은 유사한 문제를 다룬 기존 질문들입니다:
onCreate is not a function 에러 - 유사한 문제로 인해 발생한 에러를 다룹니다.
작성완료 버튼 후 onCreate is not a function 에러 -
context사용 시 나타나는 문제를 해결합니다.작성완료 시 onCreate 함수 호출 못함 -
context사용 및 함수 호출 문제를 다룹니다.
위의 링크를 따라 유사한 상황에서의 해결책을 참고하시면 오류 해결에 도움이 될 것입니다.
저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.
useEffect와 lifecycle문의
0
32
2
프론트엔드 학습 수준 문의
0
44
2
리액트 챕터별 코드에서 eslint 설정파일이 없어요
0
51
2
데이터 로딩중 화면만 계속 나와요!!
0
56
2
퍼블리셔일경우 어느정도 수준까지 강의를 들어야할까요
0
80
2
이후의 커리큘럼 문의
0
102
2
실슬환경 설정에서 save후 console.log 부분이 새로고침이 안되는현상입니다.
0
50
2
최적화 관련 질문있습니다 (useMemo 등)
0
85
3
프로바이더 컴포넌트의 위치는 어떤 기준인가요?
1
82
3
Date 객체에 관련하여 질문드립니다.
0
85
2
리액트 개정판 교재 질문
0
60
2
예제코드가 안나와요!
0
78
2
select a variant 선택에서 javascript와 javascript+react compiler 중 무엇을 선택해야하나요? com
0
109
2
onMouseEnter 관련 문의 드립니다
0
93
3
배열의 렌더링 관련 질문 드립니다.
0
73
2
2:40초 refObj를 콘솔로 출력시 오류가 발생합니다.
0
113
2
TS, 리액트 강의중에 뭘 먼저 수강하는게 좋을까요?
0
137
2
useCallback 적용한 onCreate, onUpdate, onDelete 함수..
0
71
1
vs code 자동완성관련 문의
0
113
2
91강 useEffect내에서 상태변화함수 호출시 발생하는 에러
1
181
2
87강 필터 함수 질문
0
69
2
useRef, useState count 비교
0
67
2
안된다고했던 이유가 무엇이었는지 모르겠습니다
0
91
2
85강에서 객체를 왜 클래스로 만들어서 new 하지 않는건지 궁금합니다.
0
76
2





