我正在尝试从另一个javascript文件加载数据,以用作我的react项目中的客户列表。 这是包含我要加载的数据的文件:
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);
});
以下是我试图在App.js中加载它的方法:
import React, { Component } from 'react';
import Customers from './Components/Customers';
import './App.css';
import './util.js';
class App extends Component {
constructor(){
super();
this.state = {}
}
componentWillMount(){
const uuidv4 = require('uuid/v4');
APICall.then(function(result){
this.setState(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;
我收到错误#34; APICall未定义&#34;。我是以错误的方式来做这件事的吗?我以为你可以访问导入文件中的任何全局变量。
答案 0 :(得分:0)
您需要导出APICall并将componentWillMount
代码移至App.js中的componentDidMount
并将setState移至客户
APICall.js
var APICall = new Promise(function(resolve, reject) {
setTimeout(resolve, 3000, customers);
});
export default APICall
App.js:
import React, { Component } from 'react';
import Customers from './Components/Customers';
import './App.css';
import './util.js';
class App extends Component {
constructor(){
super();
this.state = {}
}
componentDidMount(){//change componentWillMount to componentDidMount
const uuidv4 = require('uuid/v4');
APICall.then(function(result){
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;
希望这会有所帮助