使用Framer Motion引发页面硬重载及getServerSideProps问题求助
问题:添加motion动画后触发页面频繁硬重载及getServerSideProps异常
给div添加motion后,多个页面出现getServerSideProps相关问题。具体表现为:在展示信息表格的页面中,为表格行添加stagger动画后,页面会持续频繁硬重载;移除motion.tr组件后,该问题消失,但同时会出现无法从getServerSideProps获取homebuyers的提示。尝试更换动画类型,偶尔能短暂正常运行,但很快又会报错并触发频繁硬重载。
相关代码:
<tbody className="divide-y divide-gray-200"> {homebuyerMap.map((homebuyer, index) => ( <motion.tr key={homebuyer.id} className="hover:cursor-pointer hover:bg-gray-50" onClick={() => void router.push(`/homebuyers/${homebuyer.id}`) } initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ delay: index * 0.1 }} > <td className="whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-0"> <span className="pl-2"> {homebuyer.firstName} {homebuyer.lastName} </span> </td> <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500"> {homebuyer.address ? homebuyer.address : 'Pending'} </td> <td className="whitespace-nowrap py-4 pl-3 text-sm text-gray-500"> {homebuyer.closeDate} </td> <td className="flex justify-center whitespace-nowrap px-3 py-4 text-sm text-gray-500"> <Status status={homebuyer.status} /> </td> </motion.tr> ))} </tbody>
排查与解决建议
- 检查
homebuyerMap生成逻辑:确认getServerSideProps返回的homebuyers数据是否稳定,是否在渲染过程中被意外修改,导致组件频繁重渲染触发动画重置,进而引发页面重载。 - 优化动画配置:将
initial、animate等动画配置抽离到组件外部,避免每次渲染创建新对象触发不必要的重渲染,示例:
之后在const rowInitial = { opacity: 0, y: 20 }; const rowAnimate = { opacity: 1, y: 0 }; const getRowTransition = (index) => ({ delay: index * 0.1 });motion.tr中直接引用这些变量。 - 验证版本兼容性:确保
framer-motion版本与当前Next.js版本兼容,部分版本组合可能存在服务端渲染与客户端动画的冲突,尝试升级或降级framer-motion。 - 排查路由跳转逻辑:检查
router.push是否被意外重复触发,比如点击事件冒泡、多次绑定等,可在onClick中添加日志排查触发频率。 - 客户端组件包裹:若使用Next.js 13+ App Router,需将motion相关代码放在标记了
'use client'的组件中,避免服务端渲染时的冲突。
内容的提问来源于stack exchange,提问作者Teague Porter
相关产品推荐
相关产品推荐

