작성완료 버튼 후 onCreate is not a function 에러
706
작성한 질문수 3
import { useState, useRef, useContext } from 'react';
import { useNavigate } from 'react-router-dom';
import { DiaryDispatchContext } from './../App.js';
import MyHeader from './MyHeader';
import MyButton from './MyButton';
import EmotionItem from './EmotionItem';
//PUBLIC_URL 실해잉 안된다면,
const env = process.env;
env.PUBLIC_URL = env.PUBLIC_URL || '';
const emotionList = [
{
emotion_id:1,
emotion_img : process.env.PUBLIC_URL + `/assets/emotion1.png`,
emotion_descript:'완전 좋음',
},
{
emotion_id:2,
emotion_img : process.env.PUBLIC_URL + `/assets/emotion2.png`,
emotion_descript:'좋음',
},
{
emotion_id:3,
emotion_img : process.env.PUBLIC_URL + `/assets/emotion3.png`,
emotion_descript:'그러저럭',
},
{
emotion_id:4,
emotion_img : process.env.PUBLIC_URL + `/assets/emotion4.png`,
emotion_descript:'나쁨',
},
{
emotion_id:5,
emotion_img : process.env.PUBLIC_URL + `/assets/emotion5.png`,
emotion_descript:'끔찍함',
},
]
const getStringDate = (date) => {
return date.toISOString().slice(0,10); //toISOString->IOS 스트링을 반환해준다. YYYY-MM-DDTH -> slie잘라서 가져온다
}
const DiaryEditor = () => {
const contentRef = useRef();
const [content, setContent] = useState('');
const [emotion, setEmotion] = useState(3); //기본3번쨰 감정
const {onCreate} = useContext(DiaryDispatchContext);
const handleClickEmote = (emotion) =>{
setEmotion(emotion);
}
const [date, setDate] = useState(getStringDate(new Date()));
const navigate = useNavigate();
const handleSubmit = () => {
if( content.length < 1 ){
contentRef.current.focus();
return;
}
//onCreate함수를 불러와야한다.
onCreate(date, content, emotion);
//navigate('/', {replace:true}); //option, 뒤로가기버튼을 못오게막는다
}
return(
<div className='DiaryEditor'>
<MyHeader
headText={'새 일기쓰기'}
leftChild={
<MyButton text={'< 뒤로가기'} onClick={()=>navigate(-1)}/>
}
/>
<div>
<section>
<h4>오늘은 언제인가요?</h4>
<div className='input_box'>
<input
className='input_date'
value={date}
onChange={(e)=>setDate(e.target.value)}
type='date'
/>
</div>
</section>
<section>
<h4>오늘의 감정</h4>
<div className='input_box emotion_list_wrapper'>
{emotionList.map((it)=>(
<EmotionItem
key={it.emotion_id}
{...it}
onClick={handleClickEmote}
isSelected={it.emotion_id === emotion}
/>
))}
</div>
</section>
<section>
<h4>오늘의 일기</h4>
<div className='input_box text_wrapper'>
<textarea
placeholder="오늘은 어땠나요?"
ref={contentRef}
value={content}
onChange={(e)=>setContent(e.target.value)}
/>
</div>
</section>
<section>
<div className='control_box'>
<MyButton text={'취소하기'} onClick={()=>navigate(-1)} />
<MyButton text={'작성완료'} type={'positive'} onClick={handleSubmit} />
</div>
</section>
</div>
</div>
)
}
export default DiaryEditor;
import React,{ useReducer, useRef } from 'react';
import "./App.css";
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import New from './pages/New';
import Edit from './pages/Edit';
import Diary from './pages/Diary';
const reducer = (state, action) => {
let newState= [];
switch(action.type){
case 'INIT' : {
return action.data;
}
case 'CREATE' : {
newState = [...action.data, ...state];
break;
}
case 'REMOVE' : {
newState = state.filter((it)=>it.id !== action.targetId);
break;
}
case 'EDIT' : {
newState = state.map((it)=>it.id === action.data.id? {...action.data}:it);
break;
}
default :
return state;
}
return newState;
};
export const DiaryStateContext = React.createContext();
export const DiaryDispatchContext = React.createContext();
const dummyData = [
{
id:1,
emotion:1,
content:'오늘의 일기 1번',
date : 1659555437823, //console.log(new Date().getTime()); 값 확인해서 넣기
},
{
id:2,
emotion:2,
content:'오늘의 일기 2번',
date : 1659555437824,
},
{
id:3,
emotion:3,
content:'오늘의 일기 3번',
date : 1659555437824,
},
{
id:4,
emotion:4,
content:'오늘의 일기 4번',
date : 1659555437824,
},
{
id:5,
emotion:4,
content:'오늘의 일기 5번',
date : 1759555437824,
},
]
const App = () => {
const [data, dispatch] = useReducer(reducer, dummyData);
const dataId = useRef(0);
//CREATE
const onCreate = (date, content, emotion) => {
dispatch({
type:'CREATE',
data:{
id:dataId.current,
date : new Date(date).getTime(),
content,
emotion
},
});
dataId.current +=1;
}
//REMOVE
const onRemove = (targetId) => {
dispatch({
type:'REMOVE',targetId});
};
//EDIT
const onEdit = (targetId, content, date, emotion) => {
dispatch({
type:'EDIT',
data:{
id:targetId,
date:new Date(date).getTime(),
content,
emotion,
}
})
}
return (
<DiaryStateContext.Provider value={data}>
<DiaryDispatchContext.Provider value={[
onCreate,
onEdit,
onRemove,
]}>
<BrowserRouter>
<div className="App">
<Routes>
<Route path="/" element={<Home/>} />
<Route path="/new" element={<New/>} />
<Route path="/edit" element={<Edit/>} />
<Route path="/diary/:id" element={<Diary/>} />
</Routes>
</div>
</BrowserRouter>
</DiaryDispatchContext.Provider>
</DiaryStateContext.Provider>
);
};
export default App;
답변 1
0
안녕하세요
이정환입니다
Context Provider에게 value Prop으로 전달해야하는 값은 배열이 아닌 객체입니다.
질문 주신 코드는 다음과 같이 배열을 이용하셨습니다.
<DiaryDispatchContext.Provider value={[
onCreate,
onEdit,
onRemove,
]}>
위 코드를 아래와 같이 수정해야 합니다
<DiaryDispatchContext.Provider value={{
onCreate,
onEdit,
onRemove,
}}>
useEffect와 lifecycle문의
0
26
2
프론트엔드 학습 수준 문의
0
38
2
리액트 챕터별 코드에서 eslint 설정파일이 없어요
0
48
2
데이터 로딩중 화면만 계속 나와요!!
0
55
2
퍼블리셔일경우 어느정도 수준까지 강의를 들어야할까요
0
79
2
이후의 커리큘럼 문의
0
102
2
실슬환경 설정에서 save후 console.log 부분이 새로고침이 안되는현상입니다.
0
50
2
최적화 관련 질문있습니다 (useMemo 등)
0
84
3
프로바이더 컴포넌트의 위치는 어떤 기준인가요?
1
82
3
Date 객체에 관련하여 질문드립니다.
0
85
2
리액트 개정판 교재 질문
0
60
2
예제코드가 안나와요!
0
78
2
select a variant 선택에서 javascript와 javascript+react compiler 중 무엇을 선택해야하나요? com
0
108
2
onMouseEnter 관련 문의 드립니다
0
92
3
배열의 렌더링 관련 질문 드립니다.
0
73
2
2:40초 refObj를 콘솔로 출력시 오류가 발생합니다.
0
113
2
TS, 리액트 강의중에 뭘 먼저 수강하는게 좋을까요?
0
136
2
useCallback 적용한 onCreate, onUpdate, onDelete 함수..
0
69
1
vs code 자동완성관련 문의
0
113
2
91강 useEffect내에서 상태변화함수 호출시 발생하는 에러
1
178
2
87강 필터 함수 질문
0
69
2
useRef, useState count 비교
0
67
2
안된다고했던 이유가 무엇이었는지 모르겠습니다
0
90
2
85강에서 객체를 왜 클래스로 만들어서 new 하지 않는건지 궁금합니다.
0
75
2





