我正在做一个小的家庭项目,以提高我在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; }'.Main.tsx
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>
</>
);
};Posts.tsx
export const Posts: FC<IPost[]> = ({posts}) => {
return (
<div className='post-container'>
{posts.map((post) => (
<Post key={post._id} post={post} />
))}
</div>
);
};发布于 2021-11-08 14:47:28
问题在于你在Posts.tsx下定义道具类型的方式。任何组件属性都是通过设计一个对象来实现的,但是你将它定义为一个数组。
您是说您的道具是IPost[]类型的,然后您要对它们进行解构,以获得一个名为posts的属性。
解决这个问题的最简单的方法是为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>
);
};https://stackoverflow.com/questions/69885310
复制相似问题