我正在做一個小型家庭專案來提高我的 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>
);
};
uj5u.com熱心網友回復:
問題在于您在Posts.tsx. 任何組件道具都是設計一個物件,但您將其定義為一個陣列。
你是說你的道具是型別的IPost[],然后你正在解構它們以獲得一個名為posts.
解決這個問題的最簡單方法是為 props 創建一個新型別Posts.tsx并擁有一個poststype屬性IPost[]。
// 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>
);
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352871.html
