【问题标题】:Argument of type 'never[]' is not assignable to parameter of type 'Comment | (() => Comment)'\'never[]\' 类型的参数不可分配给 \'Comment | 类型的参数(() => 评论)\'
【发布时间】:2022-08-09 23:03:56
【问题描述】:

我已经花了几个小时试图解决这个问题,我已经使用来自同一个项目的另一个组件作为基础制作了下面的代码。我究竟做错了什么?

错误正是我在标题中所写的:\'never[]\' 类型的参数不能分配给 \'Comment | 类型的参数。 (() => 评论)\'。我认为这与上面的界面或状态有关,idk。

import React, { useState, useEffect } from \'react\';
import { collection, getDocs } from \'firebase/firestore\';
import { db } from \'../../services/firebase\';
import { CommentListDiv } from \'./styles\';

interface Comment {
  email: string;
  message: string;
  name: string;
}

const CommentList = ({ pokemon }: { pokemon: any }) => {
  const [comments, setAllComments] = useState<Comment>([]);
  const collectionRef = collection(db, `comments-${pokemon.id}`);

  const loadAllComments = async (): Promise<any> => {
    await getDocs(collectionRef).then((snapshot) => {
      const allComments: any = snapshot.docs.map((doc) => doc.data());
      console.log(allComments);
      console.log(comments);
      setAllComments(allComments);
    });
  };
  useEffect(() => {
    loadAllComments();
  });

  return (
    <div>
      <CommentListDiv>
        <h1>Comments about {pokemon.name}</h1>
        <h2>Name: {comments.name}</h2>
        <h2>E-Mail: {comments.email}</h2>
        <p>
          Message:
          <br />
          {comments.message}
        </p>
      </CommentListDiv>
    </div>
  );
};

export default CommentList;

这是两个 console.logs 的返回(返回是正确的,我所做的确切条目以及在 Firebase 上也显示:

    标签: reactjs typescript firebase


    【解决方案1】:
    useState<Comment>([]);
    

    这表示状态将只包含一个Comment,但随后您尝试将一个数组作为初始值传入。如果状态应该存储一个 cmets 数组,则执行以下操作:

    useState<Comment[]>([]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-26
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-03
      • 2021-06-09
      • 2019-12-19
      • 2021-10-03
      相关资源
      最近更新 更多