useContext gives App.js:24 Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
useContext gives App.js:24 Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
我正在我的应用程序中使用 Auth Context Provider,它已在此文件中初始化:
authState.js
import React, { useReducer, createContext, useContext } from "react";
import authReducer from "./authReducer";
const initialState = {
user: null,
};
const AuthContext = createContext();
export const AuthStateProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, initialState);
return (
<AuthContext.Provider value={[state, dispatch]}>
{children}
</AuthContext.Provider>
);
};
export const useAuthContext = () => useContext(AuthContext);
然后将此上下文导入 App.js 以获取用户身份验证详细信息:
App.js
...
...
import { useAuthContext } from './context/auth/authState';
...
...
const [{ user }, authDispatch] = useAuthContext();
我在 const [{ user }, authDispatch] = useAuthContext();
行收到错误。
我找到了这个问题的解决方案,所以我在控制台记录了 useAuthContext()
@vazsonyidl 的建议并收到了未定义的信息。因此 [state,dispatch]
不为 <App/>
组件所知。我所做的只是将我的 App
组件包装在 <AuthStateProvider></AuthStateProvider>
中,然后它就解决了。感谢@vazsonyidl 的建议。
我正在我的应用程序中使用 Auth Context Provider,它已在此文件中初始化:
authState.js
import React, { useReducer, createContext, useContext } from "react";
import authReducer from "./authReducer";
const initialState = {
user: null,
};
const AuthContext = createContext();
export const AuthStateProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, initialState);
return (
<AuthContext.Provider value={[state, dispatch]}>
{children}
</AuthContext.Provider>
);
};
export const useAuthContext = () => useContext(AuthContext);
然后将此上下文导入 App.js 以获取用户身份验证详细信息:
App.js
...
...
import { useAuthContext } from './context/auth/authState';
...
...
const [{ user }, authDispatch] = useAuthContext();
我在 const [{ user }, authDispatch] = useAuthContext();
行收到错误。
我找到了这个问题的解决方案,所以我在控制台记录了 useAuthContext()
@vazsonyidl 的建议并收到了未定义的信息。因此 [state,dispatch]
不为 <App/>
组件所知。我所做的只是将我的 App
组件包装在 <AuthStateProvider></AuthStateProvider>
中,然后它就解决了。感谢@vazsonyidl 的建议。