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

React中已导入变量仍显示undefined的条件加载问题

问题原因及解决方案

问题根源

你当前的代码存在两个核心问题:

  1. mock.js中仅用require加载了目标模块,但没有将模块的导出变量向外暴露。App.js里的静态import { Name } from './mock'根本拿不到任何值,因为mock.js本身没有导出Name。
  2. ES模块的静态import是编译阶段确定的,而require是运行时执行的,两者的执行时机不匹配,导致静态导入无法获取动态加载的变量。

修复方案

方案一:修改mock.js,动态加载并导出变量

将mock.js改为以下内容,加载对应模块后直接导出所需变量:

import { isdelhiLocation } from "../utils";

// 根据条件加载对应模块
const locationVariables = isdelhiLocation 
  ? require("./delhi.variables") 
  : require("./lucknow.variables");

// 向外导出变量
export const Name = locationVariables.Name;
export const Places = locationVariables.Places;

这样App.js里的静态导入就能正常获取Name变量了。

方案二:使用ES动态import()(推荐)

更符合现代JS/React的做法是使用动态import(),可以直接在组件中完成加载逻辑:

import { useEffect, useState } from "react";
import "./styles.css";
import { isdelhiLocation } from "./utils";

export default function App() {
  const [currentName, setCurrentName] = useState(null);

  useEffect(() => {
    // 异步加载对应模块
    const loadLocationVars = async () => {
      const vars = isdelhiLocation 
        ? await import("./delhi.variables") 
        : await import("./lucknow.variables");
      setCurrentName(vars.Name);
      console.log(vars.Name);
    };

    loadLocationVars();
  }, []);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>{currentName ? `当前地点:${currentName}` : "加载中..."}</h2>
    </div>
  );
}

这种方式不需要额外的mock.js,直接在组件中根据条件动态加载模块,并通过状态管理变量,更灵活。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 05:33:12