작성
·
603
2
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,
}}>