【发布时间】:2020-09-26 07:04:00
【问题描述】:
我们正在使用 nextjs 并在页面刷新(或首次加载)时收到此错误
我的错误是:
react-dom.development.js:88 Warning: Expected server HTML to contain a matching <tag> in <tag>.
我们的功能组件的代码如下所示:
export default MyComponent () {
if(! props.something){ // ← this is causing the problem.
return null;
}
return (
<>
HTML here ...
</>
)
}
据我了解,SSR 与客户端渲染不同,这就是 react 抱怨的原因。
应用程序运行正常,但此错误显示在控制台中,我们不希望出现太多错误,因为这可能会阻止我们在真正的错误发生时看到它们。
解决办法:
解决方案是使用动态导入并将组件调用包装到:
const MyDynamicComponent = dynamic(() => import('./myComponent'), {ssr: false});
//use it:
<MyDynamicComponent />
//OR :
const MyDynamicComponent = dynamic(() => import('./myComponent'))
//use it:
{typeof window !== 'undefined' && (
<MyDynamicComponent />
)}
【问题讨论】:
-
感叹号后面的空格是错字吗?还是在代码中?
标签: javascript reactjs next.js