4
votes

I made a Todo list with React js. This web has List and Detail pages. There is a list and 1 list has 10 items. When user scroll bottom, next page data will be loaded.

user click 40th item -> watch detail page (react-router) -> click back button

The main page scroll top of the page and get 1st page data again.

How to restore scroll position and datas without Ajax call?

When I used Vue js, i’ve used 'keep-alive' element. Help me. Thank you :)

4

4 Answers

0
votes

keep-alive is really nice. Generally, if you want to preserve state, you look at using a Flux (Redux lib) design pattern to store your data in a global store. You can even add this to a single component use case and not use it anywhere else if you wish.

If you need to keep the component around you can look at hoisting the component up and adding a "display: none" style to the component there. This will preserve the Node and thus the component state along with it.

Worth noting also is the "key" field helps the React engine figure out what tree should be unmounted and what should be kept. If you have the same component and want to preserve its state across multiple usages, maintain the key value. Conversely, if you want to ensure an unmount, just change the key value.

3
votes

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.

0
votes

Until now the awnser is no unfortunately. But there's a issue about it in React repository: https://github.com/facebook/react/issues/12039

0
votes

While searching for the same, I found this library, which is said to be doing the same. Have not used though - https://www.npmjs.com/package/react-keep-alive