1、安裝依賴
npm i -S react-activation
2、包裹根組件
import { AliveScope } from "react-activation"
<AliveScope>
<App />
</AliveScope>
3、緩存組件
import { KeepAlive } from "react-activation"
export default () => {
const [isShow, setIsShow] = useState(true)
return <div>
<button onClick={() => setIsShow(!isShow)}>切換</button>
{
isShow &&
<KeepAlive>
<Page3 />
</KeepAlive>
}
<Page4 />
</div>
}
4、路由緩存
<Route
path="/page1"
render={props => (
<KeepAlive name="/page1">
<Item {...props} />
</KeepAlive>
)}
/>
5、KeepAlive屬性
屬性名 | 類型 | 備注 |
when | Boolean、Array、Function | Boolean (true-卸載時緩存 false-卸載時不緩存) Array (第 1 位參數(shù)表示是否需要在卸載時緩存 第 2 位參數(shù)表示是否卸載? Function (返回值為上述? |
saveScrollPosition文章來源:http://www.zghlxwxcb.cn/news/detail-675018.html |
Boolean | 自動保存滾動位置(默認(rèn)true) |
name | string | 緩存標(biāo)識 |
6、手動控制緩存
使用?
withAliveScope
?或?useAliveController
?獲取控制函數(shù)文章來源地址http://www.zghlxwxcb.cn/news/detail-675018.html
import KeepAlive, { withAliveScope, useAliveController } from 'react-activation'
//hook 函數(shù)式組件
function app(){
const { drop, dropScope, clear, getCachingNodes } = useAliveController()
}
//class 類組件
@withAliveScope
class App extends Component {
render() {
const { drop, dropScope, clear, getCachingNodes } = this.props
}
}
- drop(name) 卸載緩存,不包括嵌套的KeepAlive
- dropScope(name)?卸載緩存,包括嵌套的所有KeepAlive
- refresh(name) 刷新緩存狀態(tài),不包括嵌套的KeepAlive
- refreshScope(name)?刷新緩存狀態(tài),包括嵌套的所有KeepAlive
- clear() 清空所有緩存
- getCachingNodes() 獲取所有緩存中的節(jié)點
到了這里,關(guān)于React——組件緩存 react-activation的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!