firebase 我如何访问这个taskList数组中的props?

a64a0gku  于 2023-06-24  发布在  其他
关注(0)|答案(2)|浏览(116)

我想从firestore中获取taskList数组中的props,taskList是一个对象数组,所以我不能用task.propName来访问它们吗?

function App() {
  const [taskList, setTaskList] = useState<Array<object>>()

  const taskCollectionRef = collection(db, "tasks")

  useEffect(() => {
    const getTaskList = async () => {
      // Get data from db
      try {
        const data = await getDocs(taskCollectionRef);
        const filteredData = data.docs.map((doc) => ({ ...doc.data(), id: doc.id, }));
        setTaskList(filteredData);
        console.log(taskList);
      } catch (err) {
        console.error(err);
      }
    }
    getTaskList();
  }, [])

  return (
    <>
      <TopNavbar title={siteTitle} />
      <div>
        {taskList?.map((task) => (
          <div>
            <h1>{task.title}</h1> /* Property 'title' does not exist on type 'object'. */ 
          </div>
        ))}
      </div>
      <Auth />
    </>
  )
}

export default App

我试着在useState函数中更改类型,但我不知道它除了对象数组之外还可以是什么。

r6hnlfcb

r6hnlfcb1#

您可以在贴图中投射对象:

function App() {
  const [taskList, setTaskList] = useState<Array<object>>()

  const taskCollectionRef = collection(db, "tasks")

  useEffect(() => {
    const getTaskList = async () => {
      // Get data from db
      try {
        const data = await getDocs(taskCollectionRef);
        const filteredData = data.docs.map((doc) => ({ ...doc.data(), id: doc.id, } as YOUR_OBJECT_TYPE));
        setTaskList(filteredData);
        console.log(taskList);
      } catch (err) {
        console.error(err);
      }
    }
    getTaskList();
  }, [])

  return (
    <>
      <TopNavbar title={siteTitle} />
      <div>
        {taskList?.map((task) => (
          <div>
            <h1>{task.title}</h1> /* Property 'title' does not exist on type 'object'. */ 
          </div>
        ))}
      </div>
      <Auth />
    </>
  )
}
bogh5gae

bogh5gae2#

如果你将来自API的字段作为一个类型添加,你可以这样解决它:

type Task = {
  title: string
  complete: boolean
  tags: string[]
  }
const [taskList, setTaskList] = useState<Array<Task>>()

相关问题