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
相关产品推荐
相关产品推荐

