4

I have the following code:

<View>
  <Header />
  <List />
</View>

If the user clicks on an edit button in a list item, react-router changes the page from /list to /list/{itemId}. This is a new page. After the user filled in some information and clicks on save, react-router changes back to /list. Now the full /list-page is rerendered!

Is there a way to cache a page, so react can detect the changes and rerender only them instead of the full page again?

It should also be possible to render the page directly (not over /list -> /list/{itemId}) so no modal solution I think.

I'm using react-router-redux v5.0.0-alpha.9 so the solution should be compatible with it. It should also be compatible with react-native and react-dom.

Piu130
  • 956
  • 2
  • 12
  • 24
  • 1
    This isn't a feature supported by react-router directly, but the `` component does have a `render` prop that you could use to show/hide the component rather than the default behavior of unmounting it when navigating to a new route. See https://github.com/ReactTraining/react-router/issues/4888. I'm not sure what timdorr meant by "that will have unintended side effects most likely" but I imagine that in cases like this it should be fine (unless you're doing it all over the place). – Matt Browne Feb 17 '18 at 15:47

1 Answers1

1

If you are working with react-router

Component can not be cached while going forward or back which lead to losing data and interaction while using Route

Component would be unmounted when Route was unmatched

After reading source code of Route we found that using children prop as a function could help to control rendering behavior.

Hiding instead of Removing would fix this issue.

I am already fixed it with my tools react-router-cache-route

Usage

Replace <Route> with <CacheRoute>

Replace <Switch> with <CacheSwitch>


If you want real <KeepAlive /> for React

I have my implementation react-activation

Online Demo

Usage

import KeepAlive, { AliveScope } from 'react-activation'

function App() {
  const [show, setShow] = useState(true)

  return (
    <AliveScope>
      <button onClick={() => setShow(show => !show)}>Toggle</button>
      {show && (
        <KeepAlive>
          <Test />
        </KeepAlive>
      )}
    </AliveScope>
  )
}

enter image description here

The implementation principle is easy to say.

Because React will unload components that are in the intrinsic component hierarchy, we need to extract the components in <KeepAlive>, that is, their children props, and render them into a component that will not be unloaded.

CJY0208
  • 115
  • 1
  • 5