所以我正在嘗試構建一個 useAuth 背景關系,所以在用戶登錄到應用程式后,以后可以從任何組件訪問 jwt 令牌我遇到了一個以前從未有過的奇怪編譯問題,請看截圖:

純代碼如下:
import { createContext, useContext, useReducer } from "react";
import authReducer, { initialTokenValue } from "../reducers/authReducer";
const AuthContext = createContext(initialTokenValue);
export const AuthProvider = ({ children }) => {
const [state, dispatch] = useReducer(authReducer, initialTokenValue);
const fetchNewTokenValue = (token: any) => {
dispatch({
type: "GET_AUTH_TOKEN",
payload: token,
})
};
const value = {
token: state.token,
fetchNewTokenValue,
};
//VS code complain AuthContext as: Cannot find namespace 'AuthContext'.ts(2503)
//No quick fixes available
//and Operator '<' cannot be applied to types 'boolean' and 'RegExp'.ts(2365)
//Unterminated regular expression literal.ts(1161)
//No quick fixes available
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
const useAuth = () => {
const context = useContext(AuthContext);
if (context === undefined) {
throw new Error("useAuth must be used within AuthContext");
}
return context;
}
export default useAuth;
在 theroy 中,它應該可以作業,然后我可以使用如下:

但正如您在第一個螢屏截圖中看到的那樣,我找不到擺脫紅線的方法。由于錯誤,該應用程式未運行。很奇怪..它應該作業,對吧?誰能指出我的設定有什么問題?謝謝
uj5u.com熱心網友回復:
使用 JSX(js 中的 html)時,您的檔案名應以.tsx而不是結尾.ts
uj5u.com熱心網友回復:
type AuthProviderProps {
chidren: JSX.Element
};
const AuthProvider = ({children}: AuthProviderProps) => {}
也許您可以先解決此類道具的型別錯誤并嘗試
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/479162.html
