簡體   English   中英

TypeScript 錯誤:類型 'type' 不可分配給類型 'IntrinsicAttributes & 'type' & { children?: ReactNode; }'。 如何解決?

[英]TypeScript Error: Type 'type' is not assignable to type 'IntrinsicAttributes & 'type' & { children?: ReactNode; }'. How to fix it?

我正在做一個小型家庭項目來提高我的 TS 技能。 從服務器獲取數據,一切都很好,帖子開始顯示沒有錯誤,但后來我決定將帶有地圖的代碼放在一個單獨的組件中,ts 立即給了我一個錯誤:

Type '{ posts: IPost[]; }' is not assignable to type 'IntrinsicAttributes & IPost[] & { children?: ReactNode; }'.
Property 'posts' does not exist on type 'IntrinsicAttributes & IPost[] & { children?: ReactNode; }'.

主文件

export const Main: FC = () => {
  const [posts, setPosts] = useState<IPost[]>([]);

  useEffect(() => {
    try {
      const fetchPost = async () => {
        const res = await axios.get('/posts');
        setPosts(res.data);
      };
      fetchPost();
    } catch (error) {
      console.log(error);
    }
  }, []);

  return (
    <>
      <div className='main-container'>
        <NewPosts />
        <PostSort />
        <Posts posts={posts} />
      </div>
    </>
  );
};

帖子.tsx

export const Posts: FC<IPost[]> = ({posts}) => {
  return (
    <div className='post-container'>
      {posts.map((post) => (
        <Post key={post._id} post={post} />
      ))}
    </div>
  );
};

問題在於您在Posts.tsx下定義道具類型的Posts.tsx 任何組件道具都是設計一個對象,但您將其定義為一個數組。

你是說你的 props 是IPost[]類型,然后你正在解構它們以獲得一個名為posts的屬性。

解決此問題的最簡單方法是為Posts.tsx的 props 創建一個新類型,並具有Posts.tsx IPost[]類型的屬性posts


// create a new interface for prop types
interface PostsProps{
   posts: IPost[];
}


// pass it under the FC generic
export const Posts: FC<PostsProps> = ({posts}) => {
  return (
    <div className='post-container'>
      {posts.map((post) => (
        <Post key={post._id} post={post} />
      ))}
    </div>
  );
};

暫無
暫無

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

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