簡體   English   中英

說明 Typescript 與 useState 的工作原理

[英]Clarification of how Typescript with useState works

嗨,我仍在學習 Typescript 並且我正試圖擺脫我所有的任何類型。 無論我做什么,我總是會收到此錯誤。 我的應用程序運行良好,但我知道使用任何應用程序都不好,所以我想稍微清理一下。 如果您能指出正確的方向,那將很有幫助。 或者解釋我做錯了什么。 謝謝

Argument of type 'Dispatch<SetStateAction<[] | undefined>>' is not assignable to parameter of type 'Dispatch<string[]>'.
  Type 'string[]' is not assignable to type 'SetStateAction<[] | undefined>'.
    Type 'string[]' is not assignable to type '[]'.
      Target allows only 0 element(s) but source may have more.

應用程序.tsx

const [userData, setUserData] = useState<any>();
fetchData('user', setUserData);

return
<Profile content={userData} />

Firebase.tsx

export const fetchData = async (storage: string, setData: React.Dispatch<string[]>) => {
  const q = query(collection(db, storage));
  const unsubscribe = onSnapshot(q, (querySnapshot) => {
    let array: string[] = [];
    querySnapshot.forEach((doc: any) => {
      array.push({ ...doc.data(), id: doc.id });
    });
    setData(array);
  });
  return () => unsubscribe();
};

配置文件.tsx

type Props = {
  content?: {
    firstName: string;
    lastName: string;
  }[];
  location?: string;
  image?: string;
};

const Profile: React.FC<Props> = ({ content, image }) => {}

對於您的錯誤,只需將React.Dispatch<string[]>更改為Dispatch<SetStateAction<[] | undefined>> Dispatch<SetStateAction<[] | undefined>>

由於未直接定義 state,因此 Typescript 必須知道它可能未定義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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