我正在尝试检测我的 nextjs 应用程序中的 URL 路径,并根据 中的 url 路径设置初始状态context
,但未定义窗口。我知道window
在客户端渲染之前不会被定义,但是如果我想将初始状态传递到上下文中,我会把它放在哪里?
import React, {createContext, useReducer} from "react";
import Reducer from './reducer'
const initialState = {
'about': window.location.pathname == 'about' ? true : false
};
const Store = ({children}) => {
const [state, dispatch] = useReducer(Reducer, initialState);
return (
<Context.Provider value={[state, dispatch]}>
{children}
</Context.Provider>
)
};
export const Context = createContext(initialState);
export default Store;
您可以访问RouterContext
,您可以使用pathname
它提供的价值。
import { useRouter } from 'next/router';
const Store = ({children}) => {
const router = useRouter();
const [state, dispatch] = useReducer(Reducer, {
about: router.pathname === '/about'
});
// rest of the logic
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句