【发布时间】:2022-11-28 16:28:09
【问题描述】:
尝试在新的 React 项目中通过 Firebase 实现用户授权。
import { User } from '@firebase/auth-types';
// ...
const [user, setUser] = useState<User | null>(null);
const auth = getAuth();
onAuthStateChanged(auth, (newUser) => {
setUser(newUser);
});
setUser(newUser); 上的错误:
Argument of type 'User | null' is not assignable to parameter of type 'SetStateAction<User | null>'.
Type 'User' is not assignable to type 'SetStateAction<User | null>'.
Type 'User' is missing the following properties from type 'User': linkAndRetrieveDataWithCredential, linkWithCredential, linkWithPhoneNumber, linkWithPopup, and 14 more.ts(2345)
尝试做 newUser: User 并没有修复这个错误。不确定还有什么可以尝试的,因为我是 Typescript 的新手。
该文件的全部内容:
import React, { useState } from 'react';
import { getAuth, onAuthStateChanged } from 'firebase/auth';
import { User } from '@firebase/auth-types';
function EmailPasswordForm(): JSX.Element {
const [isCreatingAccount, setIsCreatingAccount] = useState(false);
const createAccountForm = (
<>
<input placeholder="e-mail" />
<input placeholder="password" type="password" />
<input placeholder="confirm password" type="password" />
</>
);
const signInForm = (
<>
<input placeholder="e-mail" />
<input placeholder="password" type="password" />
</>
);
return (
<>
{isCreatingAccount ? createAccountForm : signInForm}
<button type="button">{isCreatingAccount ? 'create account' : 'sign in'}</button>
<button className="text-button" type="button" onClick={() => setIsCreatingAccount(!isCreatingAccount)}>
{isCreatingAccount ? 'i don\'t have an account!' : 'i already have an account!'}
</button>
</>
);
}
function SignIn(): JSX.Element {
const [user, setUser] = useState<User | null>(null);
const auth = getAuth();
onAuthStateChanged(auth, (newUser) => {
setUser(newUser);
});
if (user != null) {
return <span>you are signed in!</span>;
}
return (
<div className="center">
<EmailPasswordForm />
</div>
);
}
export default SignIn;
【问题讨论】:
标签: reactjs typescript firebase