Dmi*_*ver 11 typescript reactjs typescript-typings
我正在做一个小型家庭项目来提高我的 TS 技能。从服务器获取数据,一切都很好,帖子开始显示,没有错误,但后来我决定将带有地图的代码放在单独的组件中,ts 立即给了我一个错误:
输入 '{ posts: IPost[]; }' 不可分配给类型 'IntrinsicAttributes & IPost[] & {children?: ReactNode; }'。属性“posts”在类型“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>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
Posts.tsx
export const Posts: FC<IPost[]> = ({posts}) => {
return (
<div className='post-container'>
{posts.map((post) => (
<Post key={post._id} post={post} />
))}
</div>
);
};
Run Code Online (Sandbox Code Playgroud)
Ped*_*edo 20
问题在于您在 下定义 prop 类型的方式Posts.tsx
。任何组件 props 在设计上都是一个对象,但您将其定义为数组。
你说你的 props 是类型的IPost[]
,然后你解构它们以获得一个名为 的属性posts
。
解决此问题的最简单方法是为 的 props 创建一个新类型,并具有typePosts.tsx
属性。posts
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>
);
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36731 次 |
最近记录: |