React中typeof检查后仍出现ReferenceError问题求助
问题原因与解决方案
问题根源
你注释掉pages2和pages3的变量声明后,这两个变量属于未声明状态。在JavaScript中,访问未声明的变量会直接抛出ReferenceError——哪怕用typeof检测也无法避免,因为JS引擎根本找不到这个变量的存在,typeof操作本身就会触发变量查找,进而报错。
可行解决方案
1. 先声明变量并赋默认值(推荐,适配后续Redux场景)
先在组件中声明变量,默认设为undefined(后续从Redux读取props时,也可以通过解构赋值给默认值),这样变量存在于作用域中,typeof检测就能正常工作:
function NavMenu() { const pages = ["Home", "Supermarket", "Offers"]; const pages2 = undefined; // 模拟后端未返回的情况,后续替换为props.pages2 const pages3 = undefined; return ( // ... 原有JSX结构 ) }
如果后续从Redux获取props,直接用解构赋值带默认值更方便:
function NavMenu(props) { const pages = ["Home", "Supermarket", "Offers"]; const { pages2 = undefined, pages3 = undefined } = props; // 从props读取,默认undefined return ( // ... 原有JSX结构 ) }
2. 用可选链+逻辑与简化判断(需变量已声明)
如果变量已经声明(哪怕是undefined),可以用更简洁的可选链操作符替代typeof判断,同时结合逻辑与确保数组有内容时才渲染:
{pages2?.length && ( <> <Divider light="true" orientation="vertical" variant="middle" flexItem /> {pages2.map((page) => ( <Button key={page} className="menu-stack-header-item" sx={{ display: "block" }} > {page} </Button> ))} </> )}
pages2?.length会先判断pages2是否存在(不为null/undefined),再访问length属性,避免报错;逻辑与&&则会在数组有内容时才渲染后续JSX。
3. 临时兜底:使用typeof与全局对象(不推荐)
如果不想提前声明变量,也可以借助全局对象(比如window)兜底,但这种方式不符合组件封装原则,仅作临时应急:
{typeof window.pages2 !== "undefined" ? ( // ... 渲染内容 ) : ""}
不建议在React组件中使用全局变量,会导致组件依赖全局状态,难以维护。
修改后的完整组件示例
import { Button, Divider, Stack, Box } from "@mui/material"; import React from "react"; import "./NavMenu.style.scss"; function NavMenu(props) { const pages = ["Home", "Supermarket", "Offers"]; // 从props读取,默认undefined,适配Redux场景 const { pages2 = undefined, pages3 = undefined } = props; return ( <Stack className="menu-stack-header" direction="row" justifyContent="space-between" spacing={1} > <Box sx={{ display: "flex" }}> {pages.map((page) => ( <Button key={page} className="menu-stack-header-item" sx={{ display: "block" }} > {page} </Button> ))} {pages2?.length && ( <> <Divider light="true" orientation="vertical" variant="middle" flexItem /> {pages2.map((page) => ( <Button key={page} className="menu-stack-header-item" sx={{ display: "block" }} > {page} </Button> ))} </> )} {pages3?.length && ( <> <Divider light="true" orientation="vertical" variant="middle" flexItem /> {pages3.map((page) => ( <Button key={page} className="menu-stack-header-item" sx={{ display: "block" }} > {page} </Button> ))} </> )} </Box> </Stack> ); } export default NavMenu;
内容的提问来源于stack exchange,提问作者Shayan de
相关产品推荐
相关产品推荐

