импорт класса по умолчанию не позволит мне использовать его функции - PullRequest
0 голосов
/ 31 мая 2018

Я пытаюсь импортировать класс javascript с экспортом по умолчанию.Но я не могу использовать функции, определенные в нем.Ошибка говорит: «Uncaught TypeError: _omise2.default.setPublicKey не является функцией»

Вот файл с классом, который я пытаюсь импортировать

import { isUri } from 'valid-url';
import 'whatwg-fetch';

export default class Omise {
  constructor(config) {
    const result = verifyConfigStructure(config);
    if (result.error) {
      throw new Error(result.message);
    }

    this.config = config;
    this.publicKey = null;
    this._rpc = null;
  }

  _createRpc(callback) {
    if (this._rpc) {
      return this._rpc;
    }
    else {
      const { vaultUrl } = this.config;
      const tm = setTimeout(() => {
        this._rpc.destroy();
        this._rpc = null;

        if (callback) { callback(); }
      }, 30000);

      this._rpc = new easyXDM.Rpc({
        remote: `${vaultUrl}/provider`,
        onReady() {
          clearTimeout(tm);
        }
      }, {
        remote: {
          createToken: {}
        }
      });

      return this._rpc;
    }
  }

  setPublicKey(publicKey) {
    this.publicKey = publicKey;
    return this.publicKey;
  }

  createSource(type, options, callback) {
    const auth = btoa(this.publicKey);

    options.type = type;
    
    const url = `${this.config.interfaceUrl}/sources/`;
    fetch(url, {
      method: 'post',
      headers: {
        Authorization: `Basic ${auth}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(options),
    })
    .then(response => (
      response
        .json()
        .then(data => callback(response.status, data))
    ))
    .catch((error) => {
      callback(0, {
        code: 'create_source_error',
        error: error.message,
      })
    });
  }

  createToken(as, attributes, handler) {
    const data = {};
    data[as] = attributes;

    this._createRpc(() => {
      handler(0, {
        code: 'rpc_error',
        message: 'unable to connect to provider after timeout'
      });
    }).createToken(this.publicKey, data, (response) => {
      handler(response.status, response.data);
    }, (e) => {
      handler(e.data.status, e.data.data);
    });
  }
}

/**
 * Helper to verify config structure.
 * @param {Object} config - config for omise.js.
 */
export function verifyConfigStructure(config) {
  const result = {
    error: false,
    message: '',
  };

  if (!config.vaultUrl || !isUri(config.vaultUrl)) {
    result.message = 'Missing valutUrl';
  }
  else if (!config.cardHost || !isUri(config.cardHost)) {
    result.message = 'Missing cardHost';
  }
  else if (!config.cardUrl || !isUri(config.cardUrl)) {
    result.message = 'Missing cardUrl';
  }
  else if (!config.interfaceUrl || !isUri(config.interfaceUrl)) {
    result.message = 'Missing interfaceUrl';
  }

  result.error = result.message !== '';

  return result;
}

А вот где я его импортирую

import React, { Component } from 'react';
import { Row, Col, Alert, Card, CardHeader, CardBody, FormGroup, Label, Input, CardFooter, Button } from 'reactstrap';

import Omo from '../../lib/omise.js/dist/omise';

class CardDetails extends Component {
  constructor() {
    super();
    this.handleCardInputChange = this.handleCardInputChange.bind(this);
    this.handleCardSubmit = this.handleCardSubmit.bind(this);
  }
  handleCardSubmit() {
    console.log(Omo);
    Omo.setPublicKey('pkey_test_5c3wgv7fgu8weckek64');
    const card = {
      name: this.state.card.ccname,
      number: this.state.card.ccnumber,
      expiration_month: this.state.card.ccmonth,
      expiration_year: this.state.card.ccyear,
      security_code: this.state.card.cccvv,
    };
    Omo.createToken('card', card, (statusCode, response) => {
      if (statusCode === 200) {
        // Success: send back the TOKEN_ID to your server to create a charge.
        // The TOKEN_ID can be found in `response.id`.
        console.log('success Response');
        console.log(response);
      } else {
        // Error: display an error message. Note that `response.message` contains
        // a preformatted error message. Also note that `response.code` will be
        // "invalid_card" in case of validation error on the card.

        // Example Error displaying
        Alert(`${response.code} : ${response.message}`);
      }
    });
  }
  handleCardInputChange(event) {
    console.log('----event----');
    console.log(event);
    const { target } = event;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    console.log('---------value--------');
    console.log(value);
    const { name } = target;

    this.setState({
      card: {
        [name]: value,
      },
    });
  }
  render() {
    return (
      <Row>
        <Col xs="12" sm="6">
          <Card>
            <CardHeader>
              <strong>Credit Card</strong>
              <small> Form</small>
            </CardHeader>
            <CardBody>
              <Row>
                <Col xs="12">
                  <FormGroup>
                    <Label htmlFor="name">Name</Label>
                    <Input type="text" name="ccname" id="name" placeholder="Enter your name" required onChange={this.handleCardInputChange} />
                  </FormGroup>
                </Col>
              </Row>
              <Row>
                <Col xs="12">
                  <FormGroup>
                    <Label htmlFor="ccnumber">Credit Card Number</Label>
                    <Input type="text" name="ccnumber" id="ccnumber" placeholder="0000 0000 0000 0000" required onChange={this.handleCardInputChange} />
                  </FormGroup>
                </Col>
              </Row>
              <Row>
                <Col xs="4">
                  <FormGroup>
                    <Label htmlFor="ccmonth">Month</Label>
                    <Input type="select" name="ccmonth" id="ccmonth" onChange={this.handleCardInputChange} >
                      <option value="1">1</option>
                      <option value="2">2</option>
                      <option value="3">3</option>
                      <option value="4">4</option>
                      <option value="5">5</option>
                      <option value="6">6</option>
                      <option value="7">7</option>
                      <option value="8">8</option>
                      <option value="9">9</option>
                      <option value="10">10</option>
                      <option value="11">11</option>
                      <option value="12">12</option>
                    </Input>
                  </FormGroup>
                </Col>
                <Col xs="4">
                  <FormGroup>
                    <Label htmlFor="ccyear">Year</Label>
                    <Input type="select" name="ccyear" id="ccyear" onChange={this.handleCardInputChange} >
                      <option>2017</option>
                      <option>2018</option>
                      <option>2019</option>
                      <option>2020</option>
                      <option>2021</option>
                      <option>2022</option>
                      <option>2023</option>
                      <option>2024</option>
                      <option>2025</option>
                      <option>2026</option>
                    </Input>
                  </FormGroup>
                </Col>
                <Col xs="4">
                  <FormGroup>
                    <Label htmlFor="cvv">CVV/CVC</Label>
                    <Input type="text" name="cccvv" id="cvv" placeholder="123" required onChange={this.handleCardInputChange} />
                  </FormGroup>
                </Col>
              </Row>
            </CardBody>
            <CardFooter>
              <Button onClick={this.handleCardSubmit}>Submit</Button>
            </CardFooter>
          </Card>
        </Col>
      </Row>
    );
  }
}

export default CardDetails;

Я пытаюсь использовать функцию setPublicKey и функцию createToken, и появляется описанная выше ошибка.

Я импортирую файл javascript, созданный после запуска npmЗапустите сборку вместо исходного файла Omise.js.Я импортирую это неправильно?

Ответы [ 2 ]

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

Вот как я это реализовал @ CertainPerformance

import Omo from '../../lib/omise.js/dist/omise';
import Config from '../../lib/omise.js/src/config';

class CardDetails extends Component {
  constructor() {
    super();
    this.handleCardInputChange = this.handleCardInputChange.bind(this);
    this.handleCardSubmit = this.handleCardSubmit.bind(this);
  }
  handleCardSubmit() {
    const Omise = new Omo(Config);
    console.log(Omo);
    Omise.setPublicKey('pkey_test_5c3wgv7fgu8weckek64');

Извините за недостаток знаний в этом.Теперь я получаю сообщение об ошибке "_omise2.default не является конструктором"

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

Вы не создали экземпляр класса после того, как импортировали его.Таким образом, вы можете получить доступ только к static ученикам.

...
handleCardSubmit() {
  // Instantiate the class
  const omo = new Omise(config);
  // Then use the methods
  omo.setPublicKey('pkey_test_5c3wgv7fgu8weckek64');
  ...
}
...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...