【发布时间】: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>
);
这给了我重新加载页面时的原始错误,所以回到第一格。
【问题讨论】:
-
你确定错误是因为这个组件吗?
-
几乎是肯定的,因为如果我注释掉搜索栏,重新加载时不会出现错误。
标签: javascript html reactjs next.js