컴포넌트를 라우터에 따라 재사용할 때 이전의 내용이 남아 있는 현상을 초기화 하는 방법 (Reset the old contents/state of the component when it is reused by the router)

배경화면을 보여주는 SPA를 만들때 겪은 일입니다.
아래 라우터로 배경화면의 상세페이지를 보여주는데요.

<Route path="backgrounds/:uuid" component={Backgrounds}/>

컴포넌트를 재사용하다보니 다시 들어갈 때 이전의 배경화면 내용이 보였다가 새로운 것으로 그려지는 현상을 겪었습니다.
리액트 컴포넌트의 생명주기를 생각해보면 당연한 일이겠죠.

그래서 이걸 여러가지 방법으로 처리해보다가 골치가 아파서 가장 간단하고 무식하게 처리를 해버렸죠.

<Route path="/" component={App}>
  <Route path="backgrounds/:uuid" component={Backgrounds}/>

방법은 라우터에서 Backgrounds를 감싸고 있는 App 컴포넌트에다가 아래 코드를 추가했습니다.

  componentWillReceiveProps(nextProps) {
    const _nowPathname = this.props.pathname;
    const _nextPathname = nextProps.pathname;
    if (_nowPathname.indexOf('backgrounds/') > -1 && _nextPathname.indexOf('backgrounds/') === -1) {
      // backgrounds clean
      const {dispatch} = this.context.store;
      dispatch(setBackgroundData(null, {}));
    }
  }

처음 React를 배울때 작성한 코드다보니 store를 직접 호출하고 있고 패턴이 좋지 않네요…

게다가 위 코드는 props가 바뀔때마다 호출되기 때문에 오버해드를 가지고 있습니다… 영 좋지 않네요…

이렇게 초기화가 필요한 상황에서 어떻게 처리하시나요?

1개의 좋아요

@realrap 님이 @@router/LOCATION_CHANGE를 쓰신다고 하셔서 찾아봤는데요.

history.listen이 더 좋은 방법일것 같습니다.

const history = syncHistoryWithStore(browserHistory, store)

history.listen(location => analyticsService.track(location.pathname))
1개의 좋아요