Как получить доступ к переменной из другого файла JavaScript, чтобы загрузить состояние - PullRequest
0 голосов
/ 10 мая 2018

Я пытаюсь загрузить данные из другого файла javascript для использования в качестве списка клиентов в моем реактивном проекте. Вот файл с данными, которые я пытаюсь загрузить:

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;

Я получаю ошибку «APICall не определен». Я поступаю об этом неправильно? Я думал, что вы можете получить доступ к любой глобальной переменной в импортируемых файлах.

1 Ответ

0 голосов
/ 10 мая 2018

Вам необходимо экспортировать APICall и переместить код componentWillMount в componentDidMount в App.js и установить для клиентов значение

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;

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...