在React Native中使用构造函数创建对象

时间:2020-04-16 12:49:49

标签: javascript react-native

我正在尝试使用传递json对象的构造函数创建RN对象,但出现“ ReferenceError:找不到变量:Product”。

Product.js

export default class Product {
    constructor(product) {
        this.name = product.name
        this.items = product.Items
        this.price = product.Price
        this.productID = product.ProductID 
        this.medias = product.Medias
        this.imageSmall = BASE_IMAGES_URL + product.MediaSmall
        this.imageLarge = this.getImageLarge(product.Medias)
    }
}

PDP.js

import { Product } from '../models/Product'
class PDP extends Component {
 render() {

    var imagesProd = [];
    var product = new Product(this.props.navigation.state.params.currentProduct);
      ....
}
}

问题是new Product()直接使用this.props.navigation.state.params.currentProduct可以正常工作。

编辑

按照您的提示,我将导入更改为import Product from '../models/Product',但是我得到了

TypeError:TypeError:TypeError:TypeError:undefined不是 构造函数(评估“新的P.default(s)”)

2 个答案:

答案 0 :(得分:1)

问题与您的导入有关。您在Product类中使用了默认导出,因此您的导入应为

import Product from '../models/Product'

答案 1 :(得分:0)

PDP.js中的第一行应为import Product from '../models/Product'

在这里查看有关导入的一些详细信息。 When should I use curly braces for ES6 import?