您好,所以我是 typescript react 的新手,目前正在嘗試使用來自 youtube 的 typescript 和教程制作應用程式。
const RegisterCustomer: React.FC = () => {
const [text, setText] = useState<string>('');
const [email, setEmail] = useState<string>('');
const [username, setUsername] = useState<string>('');
const [password, setPassword] = useState<string>('');
const [isSubmitting, setIsSubmitting] = useState(false);
const { register } = useAuth();
return (
<IonPage>
<Register />
<IonContent className="body">
<IonGrid className="gridinput1">
</IonGrid>
<IonGrid className="gridinput2">
<IonRow>
<IonInput type="email" className="inputEmail" value={email} placeholder="Email" onIonChange={e => setEmail(e.detail.value!)}></IonInput>
</IonRow>
</IonGrid>
<IonGrid className="gridinput3">
<IonRow>
<IonInput type="password" className="inputEmail" value={password} placeholder="Password" onIonChange={e => setPassword(e.detail.value!)}></IonInput>
</IonRow>
</IonGrid>
<IonGrid className="gridinput1">
<IonRow>
<IonButton onClick={async e =>{
e.preventDefault()
const res = await register(email, password);
if(res) {
console.log(res);
}
else {
//handle null response
}
console.log(email, password)
}} className="buttonLogin" expand="block" size="default" color="new">
Register Now
</IonButton>
</IonRow>
</IonGrid>
<p className="loginSeller"><a href="https://www.w3schools.com/">Are you a seller? Login as Seller</a></p>
</IonContent>
</IonPage>
);
};
export default RegisterCustomer;
這是 authContext
type ButtonProps = {
children: ReactNode;
}
export const useAuth = () =>useContext(AuthContext);
type AuthContextType = {
currentUser: null;
register: (
email: string,
password: string
) => Promise<UserCredential | undefined>;
};
const AuthContext = createContext<Partial<AuthContextType>>({}); // Partial
export default function AuthContextProvider( { children} : ButtonProps){
const [currentUser, setCurrentUser] = useState(null);
function register(email: string, password:string) {
return createUserWithEmailAndPassword(auth, email, password)
}
const value = {
currentUser,
register,
}
return <AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
}
我試圖從暫存器獲取資料到firebase,但我遇到錯誤“無法呼叫可能是'未定義'的物件。”在register.then在RegisterCustomer頁面中。我該如何解決這個問題
uj5u.com熱心網友回復:
由于您希望該register屬性始終存在,因此請調整您的型別以使其保持為必需屬性:
const AuthContext = createContext<Partial<Omit<AuthContextType, "register">> & Pick<AuthContextType, "register">>({});
在這里,型別被分成兩部分。Partial<Omit<AuthContextType, "register">>創建一個洗掉屬性并將register其他所有內容標記為可選的型別。Pick<AuthContextType, "register">創建一個僅具有該register屬性的型別。我們使用交集 ( &) 將它們組合在一起以獲得最終型別,這使得除了 register可選之外的所有內容。
這將產生一個額外的錯誤,因為您{}作為默認值傳遞,但型別表明該背景關系中必須register存在屬性。由于它只是默認值,并且您在使用提供程式時會覆寫它,因此我建議將無操作函式作為默認值傳遞給它。例如:register
const AuthContext = createContext<Partial<Omit<AuthContextType, "register">> & Pick<AuthContextType, "register">>({register: async () => undefined});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/484888.html
