Skip to content

Commit

Permalink
fix: #92
Browse files Browse the repository at this point in the history
  • Loading branch information
solarjoker committed Jan 12, 2022
1 parent e26b293 commit cd4ad98
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
10 changes: 6 additions & 4 deletions src/keep-alive/withKeepAlive.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import React, { useContext, useRef, useEffect } from 'react'
import CacheContext from './CacheContext'
import * as cacheTypes from './cache-types'
const withKeepAlive = (OldComponent, { cacheId = window.location.pathname }) => {
const withKeepAlive = (OldComponent) => {
const keepAliveWrapper = (props) => {
const { mount, cacheStates, dispatch } = useContext(CacheContext)
const ref = useRef(null)

useEffect(() => {
const cacheState = cacheStates[cacheId]
const cacheState = cacheStates[props.match.url]
if (cacheState && cacheState.doms && cacheState.status !== cacheTypes.DESTROY) {
const doms = cacheState.doms
// 先清空 childNodes 再注入
ref.current.childNodes.forEach((child) => ref.current.removeChild(child))
doms.forEach((dom) => ref.current.appendChild(dom))
} else {
mount({ cacheId, element: <OldComponent {...props} dispatch={dispatch} /> })
mount({ cacheId: props.match.url, element: <OldComponent {...props} dispatch={dispatch} /> })
}
}, [cacheStates, dispatch, mount, props])

return <div id={`keepalive_${cacheId}`} ref={ref} />
return <div id={`keepalive_${props.match.url}`} ref={ref} />
}
return keepAliveWrapper
}
Expand Down
2 changes: 1 addition & 1 deletion src/util/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export const existKeepAliveRouter = (routes, withKeepAlive) => {
const { path, component, children, keepAlive, scroll } = router
isExist = isExist || keepAlive
if (keepAlive && path) {
router.component = withKeepAlive(component, { cacheId: path, scroll })
router.component = withKeepAlive(component, { scroll })
}
if (children) {
getKeepAlive(children)
Expand Down

0 comments on commit cd4ad98

Please sign in to comment.