[英]State is always undefined in nextjs useReducer and useContext
我在我的 nextjs 项目中使用上下文 api 但每当我尝试使用上下文 api 从 state 获取值时,它总是抛出错误“未定义”
AppReducer.js
const initialState = { isMobile: false, user: {}, }; export const AppReducer = (state = initialState, action) => { switch (action.type) { case "init_stored": { return action.value; } case "setMobile": { return {...state, isMobile: (typeof window.== "undefined") && window,innerWidth <= 768; }: } case "setUser". { return {..,state: user. action,payload; }: } default; { return state; } } };
AppContext.js
import { createContext, useContext, useMemo, useReducer } from "react"; import { AppReducer, initialState } from "./AppReducer"; const AppContext = createContext(); export function AppWrapper({ children }) { const { state, dispatch } = useReducer(AppReducer); console.log("AppWrapper: state", state); const contextValue = useMemo(() => { return { state, dispatch }; }, [state, dispatch]); return ( <AppContext.Provider value={contextValue}>{children}</AppContext.Provider> ); } export function useAppContext() { return useContext(AppContext); }
_app.js
import { AppWrapper } from 'context/AppContext' import Layout from '@/components/layout' function MyApp({ Component, pageProps }) { return ( <AppWrapper> <Layout> <Component {...pageProps} /> </Layout> </AppWrapper> ) } export default MyApp
我正在尝试像这样在我的主页中访问它
const { state } = useAppContext(); console.log(state, 'state');
请帮助我做错了什么或我在这里遗漏了什么?
终于找到了)。 使用 [] 而不是 {}
const [state, dispatch] = useReducer(AppReducer, { initialState: 'test'});
并在首页拨打state
const state = useAppContext()
请使用这种方式
mport { createContext, useContext, useMemo, useReducer } from "react";
import { AppReducer, initialState } from "./AppReducer";
const AppContext = createContext({});
export function AppWrapper({ children }) {
const [ state, dispatch ] = useReducer(AppReducer);
console.log("AppWrapper: state", state);
return (
<AppContext.Provider value={{state, dispatch}}>{children}</AppContext.Provider>
);
}
export function useAppContext() {
return useContext(AppContext);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.