我正在处理一个Next.js项目,但是一直遇到一个hydration错误。我看到的具体错误信息是:
错误:hydration失败,因为初始UI与在服务器端渲染时呈现的内容不匹配。
警告:期望服务器HTML中包含匹配的<div>。
我理解这可能是由于服务器端渲染(SSR)HTML与React在客户端进行hydration期间生成的HTML不匹配所致。警告提示在服务器渲染的HTML中期望找到一个<div>标签,但未找到。
import React from 'react';
import styled from 'styled-components';
import {
FaIcon1 as Icon1,
FaIcon2 as Icon2,
FaIcon3 as Icon3,
FaIcon4 as Icon4
} from 'react-icons/fa';
import Link from 'next/link';
const Container = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background: #ffffff;
`;
const ListItemContainer = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
width: 70%;
overflow-y: auto;
@media (min-width: 768px) {
flex-direction: row;
}
`;
const ListItem = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 10px;
margin: 10px 10px;
font-size: 1.8em;
border: 1px solid #299d51;
border-radius: 5px;
cursor: pointer;
color: #14080e;
transition: background 0.3s;
width: 50vw;
min-height: 20vh;
text-align: center;
&:hover {
background: #4cb16b;
}
@media (min-width: 768px) {
width: 20vw;
}
svg {
color: #00722e;
margin-bottom: 20px;
}
`;
const Home: React.FC = () => {
return (
Item 1
Item 2
Item 3
Item 4
);
};
export default Home;
如何在NextJS 13中修复此错误?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
问题是由Next.js的组件引起的。我通过用标准的<a>标签替换了该组件来修复它:
<a href="/stock"> <ListItem> <Icon1 size={70} /> 项目1 </ListItem> </a>这样在点击链接时会强制进行整个页面刷新,而不像该组件那样启用客户端导航。请注意,这是一个解决方法,可能会由于页面重新加载而影响性能。