简体   繁体   English

当你想要.map数据时,如何用UseState和Firebase快照定义类型?

[英]How to define type with UseState and Firebase snapshot when you want to .map the data?

Relevant Code:相关代码:

const [posts, setPosts] = useState([]);

 useEffect(
    () =>
      onSnapshot(
        query(collection(db, "posts"), orderBy("timestamp", "desc")),
        (snapshot) => {
          setPosts(snapshot.docs);
        }
      ),
    [db]
  );

 return (
 <div>
   {posts.map((post) => (
      <Post key={post.id} id={post.id} post={post.data()} />
    ))}
 </div>
)

The above code does run fine locally, but for deployment it seems like UseState being [] or undefined or null with.map is throwing an error.上面的代码在本地运行良好,但对于部署来说,似乎 UseState 是 [] 或 undefined 或 null with.map 抛出错误。

Errors I've gotten so far:到目前为止我遇到的错误:

1: Type 'QueryDocumentSnapshot[]' is not assignable to type 'never[]'. 1:类型“QueryDocumentSnapshot[]”不可分配给类型“never[]”。

So I tried altering UseState and snapshot as any, then we get error 2所以我尝试改变 UseState 和快照,然后我们得到错误 2

2: Type error: Parameter 'post' implicitly has an 'any' type. 2:类型错误:参数“post”隐式具有“any”类型。

Then, I tried using String[] but that didn't work either然后,我尝试使用 String[] 但这也不起作用

Then, I tried moving.map up (snapshot.docs.map) to get error 3然后,我尝试向上移动.map (snapshot.docs.map) 得到错误 3

3: TypeError: Cannot read properties of null (reading 'map') 3:类型错误:无法读取 null 的属性(读取“地图”)

Any help would be greatly appreciated!任何帮助将不胜感激!

First, you can create an interface for your Post document.首先,您可以为您的Post文档创建一个界面。 For example,例如,

interface IPost {
  id: string
  title: string
  // other fields
}

Then you can use it with useState to define the type:然后你可以将它与useState一起使用来定义类型:

const [posts, setPosts] = useState<IPost>([]);

Additionally, you can set the data itself in state instead of the QueryDocumentSnapshot array:此外,您可以将数据本身设置为 state 而不是QueryDocumentSnapshot数组:

setPosts(snapshot.docs.map((d) => ({ id: d.id, ...d.data() })) as IPost[])
return (
 <div>
   {posts.map((post) => (
      <Post key={post.id} id={post.id} post={post} />
    ))}
 </div>
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM