Framer Motion 和 React 路由器 5:如何防止使用嵌套路由重新渲染父组件? [英] Framer Motion and React router 5: How do I prevent re-render of parent components with nested routes?

查看:79
本文介绍了Framer Motion 和 React 路由器 5:如何防止使用嵌套路由重新渲染父组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例沙箱中,我有一个父 React Router 渲染两个动画组件.

In the example sandbox below I have a parent React Router rendering two animated components.

https://codesandbox.io/s/frame-motion-x-react-router-x-simple-tb1wg?file=/src/Routes.tsx

其中一个包含自己的嵌套链接——每个链接都有自己独立的成帧运动动画.当我单击路由链接时,我需要停止重新渲染嵌套开关的父级.我可以看到问题与在两个级别上使用切换键有关,但我不知道用什么替换它以停止重新渲染更高的组件层次结构.如果我删除键,它会破坏动画.

One of them contains its own nested links - each with their own independent framer-motion animations. I need to stop the parent of the nested switch re-rendering when i click a route link. I can see the problem is related to use of the switch key on both levels but i dont know what to replace it with to stop re-rendering higher up the component hierarchy. If I remove the key, it breaks the animation.

步骤:

选择关于.注意正确的进入和退出动画.选择联系人.注意正确的进入和退出动画.select Child 1. 注意父组件不需要的重新渲染select Child 2. 注意父组件不需要的重新渲染备注:

select About. note correct entry and exit animations. select Contact. note the correct entry and exit animations. select Child 1. note the unwanted re-render of the parent component select Child 2. note the unwanted re-render of the parent component Notes:

  • 我添加了一些内联的 Math.random() 调用,这些调用会在重新渲染时发生变化
  • 我包含了一个没有动画的顶级链接来演示嵌套组件按预期在安装时动画.然而它是仍在重新渲染选择子链接.

在选择深层嵌套链接时,location.pathname 键会强制重新渲染.我可以用什么明智地替换它,以便它不会重新渲染?我试过删除它,但这会破坏动画.

The location.pathname key is forcing re-renders when selecting deep nested links. what can i sensibly replace it with so that it doesn't re-render? Ive tried removing it, but that breaks the animation.

谢谢

推荐答案

已解决:我已将 location.pathname 替换为带有 useState 的路由器包装器上的组件特定状态键.

solved: i have replaced the location.pathname with a component specific state key on the router wrappers with useState.

https://codesandbox.io/s/framer-motion-nested-routes-react-router-747yw

结果:子路由动画独立于父路由工作,反之亦然.可以通过防止在单个链接上多次重复重新路由来改进.欢迎提出建议.

result: the child route animations work indepedently of the parent routes and vice versa. could be improved by preventing multiple repeat re-routes on single links. suggestions welcome.

这篇关于Framer Motion 和 React 路由器 5:如何防止使用嵌套路由重新渲染父组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆