将新的键值对添加到空对象将引发TypeError为null错误

时间:2019-04-11 04:33:24

标签: javascript reactjs mobx

这是我要在React应用中使用的mobx商店:

import {observable, computed, action, decorate} from 'mobx';

class Cart {
    cart = 0;
    product = {};
    loaded = false;


    addCart(product, amount) {
        if(this.product === null) {
            this.product[product] = Number(amount);
        } else {
            if (product in this.product) {
                this.product[product] = this.product[product] + Number(amount);
            } else {
                this.product[product] = Number(amount);
            }
        }
        localStorage.setItem('product', JSON.stringify(this.product));
        this.cart = this.cart + Number(amount);
    }
}

export default Cart = decorate(Cart, {
    cart: observable,
    product: observable,
    addCart: action
})

当我尝试从诸如addCart(4, 1)之类的组件中添加一些数据时,它抛出TypeError: this.product is null并在此块中显示错误

if(this.product === null) {
   this.product[product] = Number(amount);
} 

1 个答案:

答案 0 :(得分:1)

如果this.product为null,则必须先将其设置为等于空数组,然后再分配数组元素:

addCart(product, amount) {
    if(this.product === null) {
        this.product = [];  // <-- INSERT THIS LINE HERE
        this.product[product] = Number(amount);