【问题标题】:Argument of type 'User | null' is not assignable to parameter of type 'SetStateAction<User | null>'\'User | 类型的参数null\' 不可分配给类型为 \'SetStateAction<User |空>\'
【发布时间】: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


    【解决方案1】:

    首先想到的是,这个副作用应该在 useEffect 内部完成,它应该在组件第一次挂载时触发。

    useEffect(() =>{
           const unlisten = onAuthStateChanged(
              authUser => {
                authUser
                  ? setAuthUser(authUser)
                  : setAuthUser(null);
              },
           );
           return () => {
               unlisten();
           }
     }, []);
    

    然后清理效果。在我的例子中,完全相同的代码有效。

    【讨论】:

      猜你喜欢
      • 2023-01-25
      • 2021-09-04
      • 2021-07-14
      • 2020-04-17
      • 2021-08-02
      • 2021-10-19
      • 1970-01-01
      • 2021-08-20
      • 2021-10-28
      相关资源
      最近更新 更多