[React]useReducer

박성수·2022년 10월 12일
0
post-thumbnail
const [state, dispatch] = useReducer(reducer, initialState); //useReducer선언
const [a, setA] = useState(); //useState선언

위와 같이 Reducer를 선언한다.

선언한 배열의 첫 번째 인자인 state는 상태값이고 두 번째 인자인 dispatch는 행동을 추적하는 함수이다. 행동을 추적하여 감지된 행동에 따라 다른 함수를 가져와 실행할 수 있다.

useReducer의 함수의 첫 번째 인자로 받는 reducer는 함수의 이름이다. 이 함수는 상태값과 액션 두개의 인자로 갖도록 선언된다. initialState는 최초 state의 상태이다.

const reducer=(state, action)=>{
	switch(action.type){
		case "액션이름1" : 
			{이벤트에서 감지한 액션이름과 위의 경우가 같을 때 시행할 동작}
		case "액션이름2" :
			{이벤트에서 감지한 액션이름과 위의 경우가 같을 때 시행할 동작2}
		default :
		 return state 
}

reducer함수는 위와같이 선언한다.

switch문과 함께 사용되어, 동작마다 각기다른 함수를 실행시킬 수 있다.

동작의 감지는 다음과 같이 한다.

예를들어 버튼이 클릭되었을 때 동작을 감지하여 함수를 실행하고싶다.

function func1(){
	dispatch({type : "액션이름1", pispatch : {id}})
}

<button onClick={func1}>클릭하세요</button>

다음과 같이 사용되면 버튼이 클릭되면 dispatch가 액션이름 1을 감지해서 reducer함수로 돌아가 action.type과 비교할 것이다. action.type이 같은 것이 있다면 해당하는 분기로 가서 해당하는 함수를 실행시킨다.

payload는 동작시에 바라볼 값을 의미하고 dispatch의 객체 내부에 같이 써준다.

ex)사용예제 댓글 추가기능 삭제기능, 좋아요기능

const initialState = { comments : [] };

function reducer(state, action) {
  switch (action.type) {
    case "writeComment":
      const commentsValue = action.payload.commentsValue;
      const comment = {
        id: Date.now(),
        text: commentsValue,
        like: false,
      };

      return {
        comments: [...state.comments, comment],
      };
      case "clickDelete" :
        return {
          comments : state.comments.filter(item => item.id !== action.payload.id)
        };
      case "clickLike" : 
        return{
          comments : state.comments.map((item)=>{
            if(item.id === action.payload.id){
              return {...item, like : !item.like};
            }
            return item
          }),
        };
const [commentsInfo, dispatch] = useReducer( reducer , initialState);

function onSubmit(event) {
    event.preventDefault();
    dispatch({ type: "writeComment", payload: { commentsValue } });
    console.log(commentsInfo);
    setCommentsValue("");
  }
function deleteClick() {
    dispatch({ type: "clickDelete", payload: { id } });
  }
function likeClick(event) {
    dispatch({ type: "clickLike", payload: { id } });
    console.log(event.target);
  }
return (
profile
Front-end Developer

0개의 댓글