这是我第一次使用 next.js,我遇到了一些问题......
所以我只是正常地运行我的应用程序,我查看了开发工具,发现了这个问题
现在,我的第一个想法是,好吧,我没有关闭 html 标签,我查看了我的导航栏和 AuthContext 组件,这不是问题,所以,我真的不知道发生了什么,我希望你能帮助我。
让我向您展示组件
导航栏
import { NavbarHeader } from "./NavbarStyled";
import Part1 from "./Parts/Part1";
import Part2 from "./Parts/Part2";
import Part3 from "./Parts/Part3";
const Navbar = () => {
if (typeof window !== "undefined") {
var auth = JSON.parse(localStorage.getItem("Auth"));
}
return (
<>
{auth ? (
<NavbarHeader>
{/* Go home icon - search bar */}
<Part1 />
{/* Middle Icons */}
<Part2 />
{/* User information */}
<Part3 />
</NavbarHeader>
) : (
<div></div>
)}
</>
);
};
export default Navbar;
这是 AuthContext
import { createContext } from "react";
import {
Actions,
dataObject,
LOGIN,
LOGOUT,
LOGINLOADING,
LOGINNOLOADING,
REGISTERLOADING,
REGISTERNOLOADING
} from "../GlobalInterfaces/AuthContextInterfaces";
import { useReducer } from "react";
import { useContext } from "react";
interface Istate {
loginLoading: boolean;
registerLoading: boolean;
data?: dataObject | null;
}
const DefaultState = createContext<Istate>({
loginLoading: false,
registerLoading: false
});
const DispatchActions = createContext(null);
const localReducer = (state: Istate, action: Actions): Istate => {
switch (action.type) {
case LOGINLOADING:
return {
...state,
loginLoading: true
};
case LOGINNOLOADING:
return {
...state,
loginLoading: false
};
case REGISTERLOADING:
return {
...state,
registerLoading: true
};
case REGISTERNOLOADING:
return {
...state,
registerLoading: false
};
case LOGIN:
localStorage.setItem("Auth", JSON.stringify({ ...action.payload }));
return {
...state,
loginLoading: false,
registerLoading: false,
data: action.payload
};
case LOGOUT:
localStorage.removeItem("Auth");
return {
...state,
data: null
};
default:
return state;
}
};
export const AuthContext = ({ children }: { children: React.ReactNode }) => {
const [state, dispatch] = useReducer(localReducer, {
registerLoading: false,
loginLoading: false,
data: null
});
return (
<DefaultState.Provider value={state}>
<DispatchActions.Provider value={dispatch}>
{children}
</DispatchActions.Provider>
</DefaultState.Provider>
);
};
export const AuthData = () => useContext(DefaultState);
export const AuthActions = () => useContext(DispatchActions);
这个问题是什么意思,可能是什么原因造成的?
感谢您的宝贵时间!
最佳答案
您的服务器和浏览器呈现的 html 输出不匹配。我相信罪魁祸首是你的Navbar
组件,html
在服务器上生成的只是一个空div,而在浏览器中它将是 <NavBarHeader>
内容。
您需要运行 auth
仅在浏览器中的逻辑,在 Next.js 中执行此操作的方式是使用 useEffect
.
//Navbar
const [auth,setAuth] = useState()
useEffect(()=>{
var auth = JSON.parse(localStorage.getItem("Auth"));
setAuth(auth)
},[])
关于reactjs - 警告 : Expected server HTML to contain a matching <section> in <div>. ---- Next.js/react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67652569/