[英]getting typeError while using dispatch from react context-api
I have created a context store using react context API and I a function to dispatch action on the state but every time I call the function I am getttype errorpeError: dispatch is not a function```我已经使用反应上下文 API 创建了一个上下文存储,并且我创建了一个函数来调度对状态的操作,但是每次我调用该函数时,我都是 getttype errorpeError: dispatch is not a function```
the implementation is of login for the user in react using context API to store the state my context provider / auth context provider该实现是用户登录以使用上下文 API 存储状态我的上下文提供者/身份验证上下文提供者做出反应
const INITIAL_STATE = {
user: JSON.parse(localStorage.getItem("user")) || null,
isFetching: false,
error: false,
};
export const AuthContext = createContext(INITIAL_STATE);
export const AuthContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);
useEffect(() => {
localStorage.setItem("user", JSON.stringify(state.user));
}, [state.user]);
return (
<AuthContext.Provider
value={{
user: state.user,
isFetching: state.isFetching,
error: state.error,
dispatch: dispatch,
}}
>
{children}
</AuthContext.Provider>
);
};
and every time I useContext to get the values of user,isFetching,error,dispatch
I am getting undefined for dispatch but the other values are coming correct isFetching is coming false as it should be initially but the value of dispatch is coming undefined.每次我使用上下文获取
user,isFetching,error,dispatch
的值时,我都无法定义调度,但其他值会正确,isFetching 会出现错误,因为它最初应该是错误的,但调度的值是未定义的。
where I am using the context我在哪里使用上下文
const { isFetching, dispatch } = useContext(AuthContext);
const handleClick = (e) => {
e.preventDefault();
console.log({ isFetching, dispatch });
dispatch({ type: "LOGIN_START" });
e.preventDefault();
loginCall(
{ email: email.current.value, password: password.current.value },
dispatch
);
};
login call function登录调用功能
export const loginCall = async (userCredential, dispatch) => {
dispatch({ type: "LOGIN_START" });
try {
const res = await axios.post("/auth/login", userCredential);
dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
} catch (err) {
dispatch({ type: "LOGIN_FAILURE", payload: err });
}
};
You need to import AuthContextProvider in index.js
and add this snipet您需要在
index.js
中导入 AuthContextProvider 并添加此代码段
<AuthContextProvider>
<App/>
</AuthContextProvider>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.