【问题标题】:Nextjs Warning: Expected server HTML to contain a matching <div> in <div> when using conditional renderingNextjs 警告:使用条件渲染时,预期服务器 HTML 在 <div> 中包含匹配的 <div>
【发布时间】:2021-08-16 22:17:39
【问题描述】:

这里和 Google 上都有类似的问题,但没有一个适合我的情况的答案。

基本上,我想在标题中显示不同的搜索栏,具体取决于我所在的页面。这是nextjs。

但是在重新加载页面时,我在控制台中收到错误:

Warning: Expected server HTML to contain a matching <div> in <div>

我尝试的第一件事是

const currentPath =  Router.router?.route;

return (
      <div className="sub-bar">
        {currentPath === '/products' && (
          <Search />
        )}
       
        {currentPath === '/baseballcards' && (
          <SearchBaseballCards />
        )}
      </div>
);

这会在重新加载页面时产生错误,即使我将其中任何一个注释掉。

接下来我尝试的是三元路由:

      <div className="sub-bar">

        {currentPath === '/baseballcards' ? <SearchBaseballCards /> : <Search />}

      </div>

这确实有效,但三元并不好,因为我只想要 /products 和 /baseballcards 页面上的搜索栏。

我尝试的最后一件事是:

  const currentPath =  Router.router?.route;
  let searchbar;

  if (currentPath === '/baseballcards') {
    searchbar = <SearchBaseballCards />
  } 
  else if (currentPath === '/products') {
    searchbar = <Search />
  }
  else {
    searchbar = null;
  }

return (
      <div className="sub-bar">

        {searchbar}

      </div>
);

这给了我重新加载页面时的原始错误,所以回到第一格。

https://reactjs.org/docs/conditional-rendering.html

【问题讨论】:

  • 你确定错误是因为这个组件吗?
  • 几乎是肯定的,因为如果我注释掉搜索栏,重新加载时不会出现错误。

标签: javascript html reactjs next.js


【解决方案1】:

与其直接使用Router.router?.route 访问Router 对象,不如使用useRouter 挂钩返回的路由器实例。这样可以保证服务端和客户端的渲染是一致的。

import { useRouter } from 'next/router';

const SearchBar = () => {
    const router = useRouter();
    const currentPath = router.asPath;

    return (
        <div className="sub-bar">
            {currentPath === '/products' && (
                <Search />
            )}
            {currentPath === '/baseballcards' && (
                <SearchBaseballCards />
            )}
        </div>
    );
};

【讨论】:

  • 就是这样。
猜你喜欢
  • 2021-01-15
  • 2020-07-04
  • 1970-01-01
  • 2021-08-11
  • 2021-08-19
  • 2021-09-05
  • 1970-01-01
  • 2018-03-08
  • 2020-11-07
相关资源
最近更新 更多