리액트 - redux-saga 라우터 연동

정영찬·2022년 4월 28일
0

리액트

목록 보기
77/79
post-thumbnail

redux-saga에서 라우터 연동을 해보자

root경로 index.js에서 전에 작성했던 sagaMiddleware에 context를 추가한다.

const sagaMiddleware = createSagaMiddleware({
  context: {
    history: customHistory
  }
});

module/posts.js 에서 버튼을 누르면 홈화면으로 돌아가는 goToHome을 thunk 함수의 형태로 작성했지만, 이번에는 saga를 사용해서 작성할 것이다. 먼저 GO_TO_HOME type 과 type 생성함수인 goToHome을 작성한다.

export const goToHome = () => ({type: GO_TO_HOME})

url 경로를 /로 변경하는 generator 함수 goToHomeSaga()를 작성한다.

function* goToHomeSaga(){
  const history = yield getContext('history');
  history.push('/');
}

postsSage함수에 모니터링 목록에 goToHomeSage를 추가한다.

export function* postsSaga(){
  yield takeEvery(GET_POSTS, getPostsSaga);
  yield takeEvery(GET_POST, getPostSaga);
  yield takeEvery(GO_TO_HOME, goToHomeSaga);
};

그리고 다시 실행해보면


제대로 동작한다.

profile
개발자 꿈나무

0개의 댓글