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

Next.js 13构建时参数解构报错:无法读取undefined属性

Next.js 13.1.2 构建时params参数异常触发TypeError问题

执行npm run build时出现以下错误:

TypeError: Cannot read properties of undefined (reading '%5Bdifficulty%5D')

问题情况

  • 首次使用Next.js框架,开发环境运行正常,仅构建阶段报错
  • 路由为/levels/[level]/[difficulty],从params解构level和difficulty时,拿到的不是预期的easy/1等值,而是%5Bdifficulty%5D/%5Blevel%5D这类URL编码字符串

相关代码

路由对应page.jsx文件(/levels/[level]/[difficulty]/page.jsx)

export default function page({ params }) {
  const { level, difficulty } = params;

  return (
    <div className='level-container'>
      <BackButton path={`/levels/${level}`} />
      <Words level={parseInt(level)} difficulty={difficulty} />
    </div>
  );
}

报错的Words组件(@components/GameComponents/Words.jsx)

import SingleWord from './SingleWord';
import levelsData from '@/data/levels.json';
import WordsProvider from '@/contexts/WordsContext';
import { UseLevels } from '@/contexts/LevelsContext';
import LevelUnlocked from '../LevelUnlocked';

export default function Words({ level, difficulty }) {
  const words = levelsData[level - 1][difficulty];
  const { newLevelUnlocked } = UseLevels;

  return (
    <WordsProvider>
      <div className="words-container">
        {words.map((word) => (
          <SingleWord
            word={word}
            key={word}
            level={level}
            difficulty={
              difficulty === 'easy' ? 1 : difficulty === 'medium' ? 2 : 3
            }
          />
        ))}
        {newLevelUnlocked && <LevelUnlocked />}{' '}
        {/*Alert the user that a new level has been unlocked*/}
      </div>
    </WordsProvider>
  );
}

本地JSON数据文件(/data/levels.json)

[
  {
    "index": 0,
    "level" : 1,
    "easy" : ["Work", "Play", "Milk", "Game", "Year"],
    "medium" : ["Space", "Apple", "Water", "Beach", "Arrow"],
    "hard": ["Finger", "Little", "Combat", "Cloudy", "Health"]
  },
  {
    "index": 1,
    "level" : 2,
    "easy" : ["Fist", "Stop", "Tree", "Ride", "Iron"],
    "medium" : ["Ocean", "Train", "Write", "Close", "Civil"],
    "hard": ["Dolphin", "Emotion", "Phrases", "Strings", "Accords"]
  },
  {
    "index": 2,
    "level" : 3,
    "easy" : ["Jump", "Lost", "True", "Mind", "Rude"],
    "medium" : ["Grass", "Bunny", "Party", "Rugby", "Storm"],
    "hard": ["Doctor", "Little", "Accord", "Sponge", "Suffix"]
  },
  {
    "index": 3,
    "level" : 4,
    "easy" : ["Brown", "Civil", "Gests", "Sleep", "Clock"],
    "medium" : ["Hunger", "Pencil", "Shield", "Ginger", "Travel"],
    "hard": ["Academy", "Elegant", "Scholar", "Miracle", "Victory"]
  }
]

排查尝试

  • 曾认为是level为字符串类型,转为整数后问题仍未解决
  • 构建时打印levelsData[0][difficulty]结果正常,因此怀疑问题出在page.jsx获取的params参数上

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 15:50:30