You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js调用Firestore时出现TypeError: Cannot read property 'useState' of null错误求助

问题分析与修复

核心错误点

  • React Hook使用违规:useState是React Hook,必须在函数组件的顶层作用域内调用,你把它写在了Card组件外部,这直接违反了Hook的使用规则,导致出现Cannot read property 'useState' of null错误。
  • getStaticProps逻辑错误:getStaticProps是Next.js的静态数据获取函数,它运行在构建阶段/服务端,无法访问React组件的状态(比如setstudents),而且它的职责是获取数据后通过props传递给组件,不需要用状态更新函数。

修正后的代码

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

export const getStaticProps = async () => {
    const reference = collection(db, "students");
    const data = await getDocs(reference);
    // 直接处理数据,不需要调用setState
    const students = data.docs.map(doc => ({...doc.data(), id: doc.id}));

    return {
        props: { students } // 正确传递props
    }
}

function Card({students}) {
  return (
    <div>
        {students.map(student => (
            <h1 key={student.id}>{student.name}</h1> // 添加key属性避免React警告
        ))}
    </div>
  )
}

export default Card

关键修正说明

  1. 将集合引用reference移到getStaticProps内部:逻辑上更合理,数据获取的相关初始化放在数据获取函数内完成。
  2. 移除组件外部的useState:当前场景下数据通过getStaticProps以props形式传递给组件,不需要额外状态管理;若后续需在组件内修改数据,再在Card组件内部使用useState。
  3. 直接在getStaticProps中处理并返回数据:无需调用setstudents,直接将处理后的students作为props返回即可。
  4. 给列表项添加key属性:符合React列表渲染的规范,避免控制台警告。

内容的提问来源于stack exchange,提问作者Vuyi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 07:05:42