next.js出现Warning: Expected server HTML to contain a matching问题解决
文章 5361 0 0 0
发布时间:2020年04月10日

概述

在使用next.js对react进行服务端渲染的时候我们遇见如图问题,Warning: Expected server HTML to contain a matching <div> in <li>.原因是我们的页面上出现了跟服务端不匹配的标签,这个标签产生的原因就是我们动态判断显示的内容,比如说我们在登陆的时候,登陆成功是不是要显示我们的用户信息,填充到界面上,这样我们就知道页面跟服务端的页面发生了变化!

next.js出现Warning: Expected server HTML to contain a matching问题解决
错误写法(服务端渲染我们不能使用如下图方法进行权限判断)

next.js出现Warning: Expected server HTML to contain a matching问题解决

正确使用(采用dynamic动态导入)

next.js出现Warning: Expected server HTML to contain a matching问题解决

错误代码

Warning: Expected server HTML to contain a matching <div> in <li>.
    in div (created by Trigger)
    in Trigger (created by SubMenu)
    in li (created by SubMenu)
    in SubMenu (created by Connect(SubMenu))
    in Connect(SubMenu) (created by Context.Consumer)
    in SubMenu (at header.js:100)
    in ul (created by DOMWrap)
    in DOMWrap (created by SubPopupMenu)
    in SubPopupMenu (created by Connect(SubPopupMenu))
    in Connect(SubPopupMenu) (created by Menu)
    in Provider (created by Menu)
    in Menu (created by Context.Consumer)
    in InternalMenu (created by Context.Consumer)
    in Menu (at header.js:94)
    in header (created by Basic)
    in Basic (created by Context.Consumer)
    in Header (at header.js:90)
    in div (at header.js:89)
    in HeaderLayout (created by ConnectFunction)
    in ConnectFunction (created by ForwardRef(LoadableComponent))
    in ForwardRef(LoadableComponent) (at commonLayout.js:20)
    in section (created by Context.Consumer)
    in BasicLayout (created by Context.Consumer)
    in Layout (at commonLayout.js:19)
    in LocaleProvider (created by Context.Consumer)
    in SizeContextProvider (created by Context.Consumer)
    in LocaleReceiver (created by ConfigProvider)
    in ConfigProvider (at commonLayout.js:18)
    in CommonLayout (at pages/index.js:47)
    in Index (at _app.js:44)
    in Provider (at _app.js:43)
    in MyApp
    in Container (created by AppContainer)

如果不用next服务端渲染就不会出现上面问题,如果使用解决如下

ext.js 支持 JavaScript 的 TC39 提议dynamic import proposal。你可以动态导入 JavaScript 模块(如 React 组件)

我们查看官网我们可以动态导入组件而不对组件进行服务端渲染

import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(import('../components/hello3'), {
  ssr: false
})
export default () =>
  <div>
    <Header />
    <DynamicComponentWithNoSSR />
    <p>HOME PAGE is here!</p>
 </div>

把当前组件ssr关掉即可! ssr:false

评论专区
Q群
Q群
Q群
反馈
纠错
App