簡體   English   中英

使用來自 react context-api 的調度時獲取 typeError

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM