Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenmori/5dd2cda2b94e3dcccf24adc2e221621d to your computer and use it in GitHub Desktop.
Save kenmori/5dd2cda2b94e3dcccf24adc2e221621d to your computer and use it in GitHub Desktop.
Reactであるページのstate状態を保持して遷移先からのhistory-back(ブラウザバック)に対応する

Reactであるページのstate状態を保持して遷移先からのhistory-back(ブラウザバック)に対応する

方法の概要

globalなstateとして管理するのではなく、 Aページ -> Bページ -> Aページ と関連するページ内だけで状態を参照しあう風にする。

globalなstateとして管理したいなら App.providerなどから渡されたdispatchで実行すればいい。

今回のは Aページ -> Bページ -> Aページ

何かの状態を保持したobjecthistory.pushの第二引数に渡し、 それで遷移させることで、 その履歴は状態を持たせるようにする

次のページでブラウザバックをした際に window.onpopstateが発火するので、その際にdispatchして、initialStateにそのhistory.location.stateに入っている値があればそれを設定する。

それとは別に「前ページに戻る」ボタンの実装は linkのstateにそれを設定する。 historyオブジェクトを親からもらって、そこに入っているstate(前ページからonClickで渡したstate)が入っているので、それをLinkに渡す

ざっくり実装内容

状態を更新するonClick内でhistory.pushを実行する

//①
  const onClickPrev = useCallback((payload) => () =>  {
    history.push('/my/message', { pageNationStateForQueryVariables: payload, currentPage: currentPage - 1 });
    dispatch({type: 'UPDATE_PAGE_NUM', payload: -1});
  }, [currentPage]);

Bページの「戻る」ボタンに親からhistoryオブジェクトを渡して、stateを参照し、locatonStateForPageNationとして設置 Linkに

//②
<Link className="btn weak back" to={{pathname: '/my/message', state: locatonStateForPageNation}}>戻る</Link>

AページではcomponentDidMount時にhistoryのstateをpayloadに設定してdispatchを実行。stateの初期設定をする。

//③
  useEffect(() => {
    window.onpopstate = () => {
      dispatch({ type: 'UPDATE_PAGE_NUM_WITH_HISTORY_BUCK', payload: history.location.state.currentPage });
    };
    return () => window.onpopstate;
  });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment