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

使用getServerSideProps获取数据后控制台有输出但页面不渲染

问题分析与解决方案

你的代码核心问题是map回调函数没有返回JSX元素。虽然console.log(programme.title)能正常输出,但箭头函数使用大括号{}包裹时,必须显式用return返回要渲染的内容,否则map不会生成任何可渲染的元素。

修复代码

修改map部分的代码,要么添加return,要么改用小括号()包裹JSX(箭头函数小括号会自动返回内容):

import React from 'react'
import { createClient } from '@supabase/supabase-js'

export async function getServerSideProps() {
    const supabase = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!)
    const { data: programmes, error } = await supabase
            .from('Programmes')
            .select('*')
  
    // 处理Supabase请求错误
    if (error) {
        console.error('获取节目数据失败:', error)
        return { props: { programmes: [] } }
    }

    return {
      props: {
        programmes: programmes || [],
      },
    }
}

// 定义类型替代any,提升代码可读性与类型安全
interface Programme {
  id: string;
  title: string;
  show_time: string;
  description: string;
}

function Programmes({programmes}: { programmes: Programme[] }) {

  return (
    <>
        <div className='mx-auto px-12'>
            <div className='my-24  flex flex-col'>
                <h1 className='font-extrabold text-5xl'>Les programmes Natyf</h1>
                <p>Actualités, films dramatiques, comédies, documentaires, talk-shows, spectacles de variétés et d’humour hauts en couleurs et en saveurs!</p>
            </div>

            {/* 改用小括号自动返回JSX,也可以用大括号+return */}
            {programmes.map((programme) => (
                <div key={programme.id} className="mb-6">          
                    <div className="max-w-sm bg-white border border-gray-200 rounded-lg shadow dark:bg-gray-800 dark:border-gray-700">
                        <a href="#">
                            <img className="rounded-t-lg" src="/docs/images/blog/image-1.jpg" alt={programme.title} />
                        </a>
                        <div className="p-5">
                            <h5 className="text-xl tracking-tight text-transparent bg-clip-text bg-gradient-to-r from-cyan-500 to-blue-500">{programme.show_time}</h5>
                            <h2 className='text-2xl font-bold text-white'>{programme.title}</h2>
                            <p className="my-4 font-normal text-gray-700 dark:text-gray-400">{programme.description}</p>
                        </div>
                    </div>
                </div>
            ))}

       </div>
    </>
    
  )
}

export default Programmes

额外优化说明

  1. 添加key属性:map遍历生成元素时必须加唯一key,帮助React识别元素变化,避免渲染警告和性能问题。
  2. 错误处理:在getServerSideProps中处理请求错误,确保即使请求失败也返回空数组,防止页面报错。
  3. 类型定义:用interface明确数据结构,替代any提升代码可维护性。
  4. 空值兜底:返回props时给programmes设置默认空数组,避免programmes为undefined时调用map报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:47:51