reactjs 下一个js错误-类型错误:无法读取属性“useState”为空

kulphzqa  于 2022-12-26  发布在  React
关注(0)|答案(2)|浏览(185)

我一直收到此错误
TypeError:无法读取null的属性“useState”
当我尝试从firestore数据库中提取数据时,错误指向我使用useState的时候,这是我的代码的样子

import React from 'react'
import { useState } from 'react';
import { db } from '../firebaseconfig'
import { collection, getDocs } from "firebase/firestore";

const reference = collection(db, "students");
const [students, setstudents] = useState([]);

export const getStaticProps = async () => {
    const data = await getDocs(reference);
    setstudents(data.docs.map(doc => ({...doc.data(), id: doc.id})));

    return {
        props: students
    }
}
function Card({students}) {
  return (
    <div>
        {students.map(student => (
            <h1>{student.name}</h1>
        ))}
    </div>
  )
}

export default Card

我哪里做错了?

dwbf0jvd

dwbf0jvd1#

你正在使用2个react导入。请创建一个
试试这个:
从"react"导入React,{useState}

2exbekwf

2exbekwf2#

在您提供的代码片段中,状态students除了作为 prop 发送到Card组件之外没有任何其他用途。
基于nextjs文档(https://nextjs.org/docs/basic-features/data-fetching/get-static-props#using-getstaticprops-to-fetch-data-from-a-cms),像这样修改代码并尝试

import React from 'react'
import { db } from '../firebaseconfig'
import { collection, getDocs } from "firebase/firestore";

const reference = collection(db, "students");

export const getStaticProps = async () => {
    const data = await getDocs(reference);
    const students=data.docs.map(doc => ({...doc.data(), id: doc.id}));

    return {
        props: {
           students
        }
    }
}
function Card({students=[]}) {
  return (
    <div>
        {students.map(student => (
            <h1>{student.name}</h1>
        ))}
    </div>
  )
}

export default Card

相关问题