这是我要在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);
}
答案 0 :(得分:1)
如果this.product为null,则必须先将其设置为等于空数组,然后再分配数组元素:
addCart(product, amount) {
if(this.product === null) {
this.product = []; // <-- INSERT THIS LINE HERE
this.product[product] = Number(amount);