배경화면을 보여주는 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가 바뀔때마다 호출되기 때문에 오버해드를 가지고 있습니다… 영 좋지 않네요…
…
이렇게 초기화가 필요한 상황에서 어떻게 처리하시나요?