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

React项目中如何从其他JS文件获取变量以加载状态?

问题分析与解决

你遇到的APICall is not defined错误,核心原因是ES模块系统的特性:在JavaScript模块(.js文件)中,变量默认是模块私有范围,不会自动成为全局变量。你只是导入了./util.js,但没有从该模块中显式导出APICall,所以App.js无法访问到它。

下面是具体的修复步骤:

1. 修改util.js,显式导出APICall

在util.js的末尾,添加导出语句,把APICall暴露给其他模块:

var customers = [ 
  { 
    "phone": "(613)555-0125", 
    "province":"ON", 
    "city":"Ottawa", 
    "customer_info":{ 
      "last_delivery_date":null, 
      "orders_this_month":0, 
      "buyer_average_order":0.0, 
    }, 
    "country":"Canada", 
    "business_name":"Cole's Cappuccino", 
    "id": 1, 
    "catalog": { 
      "item1": "americano", 
      "item2": "espresso", 
      "item3": "frappuccino" 
    } 
  }, 
  { 
    "phone": "(403)980-8217", 
    "province":"ON", 
    "city":"Waterloo", 
    "customer_info":{ 
      "last_delivery_date":"2018-04-30T12:00:00-00:00", 
      "orders_this_month":1, 
      "buyer_average_order":5.0, 
    }, 
    "country":"Canada", 
    "business_name":"Jen's Jello", 
    "id":1, 
    "catalog": { 
      "item1": "raspberry", 
      "item2": "green apple", 
      "item3": "blueberry", 
      "item4": "grape", 
      "item5": "orange" 
    } 
  } 
];

var APICall = new Promise(function(resolve, reject) { 
  setTimeout(resolve, 3000, customers); 
});

// 新增导出语句
export default APICall;

2. 在App.js中正确导入并使用APICall

首先修改导入语句,把APICall导入进来;另外还要修复两个潜在问题:

  • componentWillMount中普通函数的this指向问题,改用箭头函数绑定组件实例
  • setState的参数错误:你需要把获取到的customers数组放到state的customers属性下,不然this.state.customers会是undefined

修改后的App.js代码:

import React, { Component } from 'react'; 
import Customers from './Components/Customers'; 
import './App.css'; 
// 正确导入APICall
import APICall from './util.js'; 

class App extends Component { 
  constructor(){ 
    super(); 
    // 初始化state的customers为空数组,避免渲染时undefined
    this.state = { customers: [] } 
  } 

  componentWillMount(){ 
    const uuidv4 = require('uuid/v4'); 
    // 改用箭头函数,确保this指向组件实例
    APICall.then(result => { 
      // 将获取到的数组赋值给state的customers属性
      this.setState({ customers: result }); 
    }); 
  } 

  render() { 
    return ( 
      <div className="customer-container"> 
        <li className="title">MY CUSTOMERS</li> 
        <Customers customers={this.state.customers} onDelete={this.handleDeleteCustomer.bind(this)}/> 
      </div> 
    ); 
  } 
} 

export default App;

额外提示

  • 注意你的customer数据中两个对象的id都是1,这可能会导致后续删除等操作出现问题,建议改成唯一值
  • componentWillMount在React新版本中已经被标记为不安全,推荐使用componentDidMount替代,效果是一样的:
    componentDidMount(){ 
      const uuidv4 = require('uuid/v4'); 
      APICall.then(result => { 
        this.setState({ customers: result }); 
      }); 
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:01:33