reactjsreact-routerreactcsstransitiongroup

Keep react-router routed-components for all history states


I make a mobile application with Cordova. Use the react-router@2.0.0 + ReactCSSTransitionGroup to implement the "card deck" animation. I have a strict Routes tree without the possibility of circular links.

To improve performance and save the state of the previous route-components, I would like to keep the whole history of them with unmounting only on pop-state or replace-state.

How to do it?


Solution

  • Maybe you can take advantage of the onEnter and onChange callbacks when configure rootRoute.

    In onEnter callback back you can record the initial route path. In onChange callback you can compare cur/next route path, check recorded path history, and record path. Therefor since you can check and compare route path every time route changes, you can stop any circular links.

    About save all component's state, if you use redux, the whole app state can save in an object, the redux store.

    If you want save component's state at that time before leave, you can dispatch a save component state action in componentWillUnmount, and recover state in componentWillMount.

    Here is a snippet:

    var rootRoute = {
        path: '/',
        onEnter: enter,
        onChange: change,
        component: MyApp,
        indexRoute: { component: Home },
        childRoutes: [
            LoginRoute,
            ...
            {path: 'home', component: Home},
            {
                path: '*',
                component: NotFound
            }
        ]
    };
    
    function enter (next) {
        // pathStore record all navigation history
        pathStore.record(next.location.pathname);
    }
    function change (cur, next, c) {
        // when hit cur path links in nav, pathname is same, key is different.
        if (cur.location.pathname !== next.location.pathname) {
            ...
        }
    }