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

Next.js中Image组件引发TypeError: 无法读取null的'default'属性

解决Next.js中Image标签引发的TypeError: Cannot read properties of null (reading 'default')

问题分析

该错误由DashboardHeader组件中的Image标签触发,核心原因包括:

  • 组件初始渲染时,useKindeBrowserClient返回的user可能未加载完成或为null,导致user?.picture值为undefined/null
  • Next.js的Image组件无法处理无效的src参数
  • 若user.picture是外部图片,未在Next.js配置中允许对应域名也可能引发类似问题

解决方案

1. 条件渲染Image组件

当user?.picture不存在时,不渲染Image或替换为占位元素:

"use client"
import { useKindeBrowserClient } from '@kinde-oss/kinde-auth-nextjs'
import Image from 'next/image';
import React from 'react'

function DashboardHeader() {
  const {user} = useKindeBrowserClient();

  return (
   <div>
    {user?.picture && (
      <Image 
        src={user.picture} 
        alt='User avatar'
        width={40}
        height={40}
        className="rounded-full"
      />
    )}
    {/* 无头像时显示占位块 */}
    {!user?.picture && (
      <div className="w-10 h-10 bg-gray-200 rounded-full"></div>
    )}
   </div>
  )
}

export default DashboardHeader

2. 为src设置默认值

当user?.picture无效时,使用本地默认图片替代:

<Image 
  src={user?.picture || '/default-avatar.png'} 
  alt='User avatar'
  width={40}
  height={40}
/>

注意:/default-avatar.png需放置在项目的public目录下。

3. 配置Next.js允许外部图片域名

如果user.picture是Kinde提供的外部图片,需在next.config.js中添加remotePatterns配置:

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'kindeusercontent.com', // 替换为Kinde头像实际域名
        pathname: '/**',
      },
    ],
  },
}

module.exports = nextConfig

4. 处理用户数据加载状态

利用useKindeBrowserClient返回的isLoading状态,避免在数据未就绪时渲染Image:

"use client"
import { useKindeBrowserClient } from '@kinde-oss/kinde-auth-nextjs'
import Image from 'next/image';
import React from 'react'

function DashboardHeader() {
  const {user, isLoading} = useKindeBrowserClient();

  if (isLoading) {
    return <div className="w-10 h-10 bg-gray-200 rounded-full animate-pulse"></div>;
  }

  return (
   <div>
    {user?.picture && (
      <Image 
        src={user.picture} 
        alt='User avatar'
        width={40}
        height={40}
      />
    )}
   </div>
  )
}

export default DashboardHeader

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 03:26:15