[英]getting typeError while using dispatch from react context-api
我已经使用反应上下文 API 创建了一个上下文存储,并且我创建了一个函数来调度对状态的操作,但是每次我调用该函数时,我都是 getttype errorpeError: dispatch is not a function```
该实现是用户登录以使用上下文 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>
);
};
每次我使用上下文获取user,isFetching,error,dispatch
的值时,我都无法定义调度,但其他值会正确,isFetching 会出现错误,因为它最初应该是错误的,但调度的值是未定义的。
我在哪里使用上下文
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
);
};
登录调用功能
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 });
}
};
您需要在index.js
中导入 AuthContextProvider 并添加此代码段
<AuthContextProvider>
<App/>
</AuthContextProvider>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.