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

Next.js13 App Directory中Supabase获取数据无法渲染求助

问题修复方案

核心问题分析

你的代码有两个关键问题导致数据无法渲染:

  1. Profile组件未接收传入的props:你在组件里定义了一个空的profile对象,完全没使用父组件传递的profile属性。
  2. 客户端组件误用NextResponse:NextResponse是服务端路由处理器的API,客户端组件里不需要导入和使用它,属于冗余代码。

分步修复

1. 修复Profile.tsx组件

修改组件,让它正确接收并使用父组件传入的profile数据:

import React from 'react'

// 匹配profiles表结构的接口
interface ProfileData {
  name?: string;
  email?: string;
  phone?: string;
  _id?: string; // 主键字段,用于列表key
}

// 组件接收props参数,解构出profile
const Profile: React.FC<{ profile: ProfileData }> = ({ profile }) => {
  return (
    <div className='justify-center items-center flex flex-col bg-green-100 p-4 rounded'>
      <p>Name: {profile.name || '未设置'}</p>
      <p>Email: {profile.email || '未设置'}</p>
      <p>Phone: {profile.phone || '未设置'}</p>
    </div>
  )
}

export default Profile

2. 修复主页面组件(profile.tsx)

去掉冗余代码,优化类型定义:

"use client"

import { useCallback, useEffect, useState } from "react"
import Search from "../search"
import { supabase } from "@/app/libs/supabase"
import { useRouter } from "next/navigation"
import toast from "react-hot-toast"
import Profile from "@/components/profile/Profile"

// 匹配profiles表的结构
interface ProfileData {
  name: string;
  phone: string;
  email: string;
  _id: string; // 主键字段
}

export default function ProfilePage() {
  // 明确类型为数组或null,避免any
  const [profiles, setProfiles] = useState<ProfileData[] | null>(null)
  const router = useRouter()

  useEffect(() => {
    fetchUserProfile()
  }, [])

  const fetchUserProfile = useCallback(async () => {
    const { data: { user } } = await supabase.auth.getUser()

    if (user) {
      const { data } = await supabase.from("profiles").select().eq('email', user.email)
      if (data) {
        setProfiles(data)
        console.log(data)
      }
    } else {
      const load = toast.loading("跳转至登录页")
      setTimeout(() => {
        toast.dismiss(load)
      }, 500)
      router.push('/')
    }
  }, [router])

  return (
    <>
      <aside className='md:py-5'>
        <Search />
      </aside>

      <section>
        <h4 className='text-bra text-2xl text-center md:text-3xl lg:text-3xl'>My Profile</h4>
        <div className="flex items-center justify-center p-4">
          {/* 检查profiles存在且有数据,避免空数组map或加载中空白 */}
          {profiles?.length > 0 ? (
            profiles.map((profile) => (
              <Profile key={profile._id} profile={profile} />
            ))
          ) : (
            <p>加载中...</p>
          )}
        </div>
      </section>
    </>
  )
}

额外优化说明

  • 给Profile组件的字段加上默认值(比如|| '未设置'),避免数据为空时显示undefined。
  • 主组件里增加了数组长度判断,避免数据加载中或为空时页面空白。
  • 重命名了User函数为fetchUserProfile,语义更清晰。
  • 去掉了无用的NextResponse相关代码,减少客户端组件冗余。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:18:12