这是我尝试在 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
并在此 block 中显示错误
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);
关于javascript - 向空对象添加新键值对抛出 TypeError is null 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55624761/