首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类型错误:类型‘TypeScript’不可分配给类型'IntrinsicAttributes &‘类型’&{IntrinsicAttributes?:ReactNode;}‘。如何修复它?

类型错误:类型‘TypeScript’不可分配给类型'IntrinsicAttributes &‘类型’&{IntrinsicAttributes?:ReactNode;}‘。如何修复它?
EN

Stack Overflow用户
提问于 2021-11-08 14:40:59
回答 1查看 90关注 0票数 0

我正在做一个小的家庭项目,以提高我在TS的技能。从服务器获取数据,一切都很好,帖子开始显示没有错误,但后来我决定将代码和地图放在一个单独的组件中,ts立即给了我一个错误:

代码语言:javascript
复制
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

代码语言:javascript
复制
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

代码语言:javascript
复制
export const Posts: FC<IPost[]> = ({posts}) => {
  return (
    <div className='post-container'>
      {posts.map((post) => (
        <Post key={post._id} post={post} />
      ))}
    </div>
  );
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-08 14:47:28

问题在于你在Posts.tsx下定义道具类型的方式。任何组件属性都是通过设计一个对象来实现的,但是你将它定义为一个数组。

您是说您的道具是IPost[]类型的,然后您要对它们进行解构,以获得一个名为posts的属性。

解决这个问题的最简单的方法是为Posts.tsx的道具创建一个新类型,并拥有一个类型为IPost[]的属性posts

代码语言:javascript
复制
// 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>
  );
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69885310

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档