javascript - 在 NEXTjs 中使用 React-Moveable 时遇到问题 : TypeError: Cannot read property 'userAgent' of undefined

标签 javascript reactjs next.js

过去几个小时我一直在努力解决这个问题。我可以通过一个简单的 node.js 应用程序很好地使用react-moveable。当我尝试在 NEXTjs 应用程序中使用相同的模块时,它会抛出错误:TypeError: Cannot read property 'userAgent' of undefined

这是重复的问题: https://codesandbox.io/s/hungry-ramanujan-ttqh3?fontsize=14&hidenavigation=1&theme=dark

据我所知,我似乎正在尝试在服务器端渲染一些本应在客户端的内容。但不确定解决方案是什么......

感谢您的帮助!

最佳答案

这里的问题是该模块尚未准备好 SSR,并且它正在尝试读取 navigator.userAgent

您可以尝试将逻辑移动到另一个组件并使用 next/dynamic 动态导入它,并将 ssr 设置为 false:

import dynamic from 'next/dynamic';

// ...
// other stuff, imports, etc
// ...

const MoveableNoSSR = dynamic(() => import('./MoveableWrapper'), {
  ssr: false,
  loading: () => <div>Loading Moveable...</div>,
});

关于javascript - 在 NEXTjs 中使用 React-Moveable 时遇到问题 : TypeError: Cannot read property 'userAgent' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59603615/

相关文章:

javascript - ES6 重新导出的值被包装到 Getter 中

javascript - Angular module.run ReferenceError : $location is not defined

javascript - 在 span 标签中包装文本

javascript - Vanilla JS 断言库替代 Meteor 的检查包

reactjs - 修复 "' Component'没有任何构造或调用签名。“Typescript 的默认 props 错误

javascript - 在 React 中 props 更改时重新渲染子组件的最佳解决方案是什么?

bootstrapping - Next.js 客户端和服务器端引导代码

reactjs - React 中 next.js 中基于角色的路由

node.js - Reactjs 无法建立套接字连接,它在调用 componentDidMount 时打开并获取响应

next.js - 如何将 nextjs 应用程序置于维护模式(使用 Vercel)