![](/img/trans.png)
[英]How to prevent re-render of parent route using React-Router and Framer Motion?
[英]Framer Motion and React router 5: How do I prevent re-render of parent components with nested routes?
在下面的示例沙箱中,我有一個父 React Router 渲染兩個動畫組件。
https://codesandbox.io/s/frame-motion-x-react-router-x-simple-tb1wg?file=/src/Routes.tsx
其中一個包含自己的嵌套鏈接——每個鏈接都有自己獨立的成幀運動動畫。 當我單擊路由鏈接時,我需要停止嵌套開關的父級重新渲染。 我可以看到問題與在兩個級別上使用 switch 鍵有關,但我不知道用什么替換它以停止重新渲染組件層次結構的更高層。 如果我刪除密鑰,它會破壞 animation。
腳步:
select 關於。 注意正確的進入和退出動畫。 select 聯系方式。 注意正確的進入和退出動畫。 select Child 1. 注意父組件不需要的重新渲染 select Child 2. 注意父組件不需要的重新渲染 注意:
location.pathname 鍵在選擇深層嵌套鏈接時強制重新渲染。 我可以用什么明智地替換它,以免它重新渲染? 我試過刪除它,但這會破壞 animation。
謝謝
已解決:我已將 location.pathname 替換為帶有 useState 的路由器包裝器上的組件特定 state 密鑰。
https://codesandbox.io/s/framer-motion-nested-routes-react-router-747yw
結果:子路由動畫獨立於父路由工作,反之亦然。 可以通過防止單個鏈路上的多次重復重新路由來改進。 歡迎提出建議。
一個更簡單的解決方案是使用根路徑名作為鍵。
例如,當 AnimatePresence 從/topics
更改為/topics/react
時,它不會重新設置開關的動畫。 因為關鍵仍然是相同的: topics
。
<AnimatePresence>
<Switch location={location} key={location.pathname.split('/')[1]}>
<Route path="/" exact>
<Home />
</Route>
<Route path="/topics">
<Topics />
</Route>
</Switch>
</AnimatePresence>
您當然可以進一步 go 並將其提取到 function ,這將為您提供適當的每個嵌套級別的密鑰。
const getPathKey = (path, level = 1) => {
// path: "/topics/react/router"
// level: 1 -> topics
// level: 2 -> topics/react
// level: 3 -> topics/react/router
return path.split('/').splice(1, level).join('/');
}
<AnimatePresence>
<Switch location={location} key={getPathKey(location.pathname)}>
...
<AnimatePresence>
<Switch location={location} key={getPathKey(location.pathname, 2)}>
...
</Switch>
</AnimatePresence>
</Switch>
</AnimatePresence>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.