向空对象添加新键值对抛出 TypeError is null 错误
add new key value pair to empty object throws TypeError is null error
这是我尝试在 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);
}
如果this.product为null,则在分配数组元素之前必须先将其设置为空数组:
addCart(product, amount) {
if(this.product === null) {
this.product = []; // <-- INSERT THIS LINE HERE
this.product[product] = Number(amount);
这是我尝试在 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);
}
如果this.product为null,则在分配数组元素之前必须先将其设置为空数组:
addCart(product, amount) {
if(this.product === null) {
this.product = []; // <-- INSERT THIS LINE HERE
this.product[product] = Number(amount);