请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

老师,我想问一个问题

老师,如果是正常对象引用的话

let shop = {}
let a = shop
a.id = 11
console.log(shop.id) // 11

如果是响应式引用的话

let shop = reactive({})
let a = shop
a.id = 11
console.log(shop.id) // 11

现在a和shop的引用地址应该一样

但是

为什么在状态管理应用中不是这样

const { shopid, productId, productInfo } = payload
let shopInfo = state.cartList[shopid]
if (!shopInfo) shopInfo = {}
let product = shopInfo[productId]
if (!product) {
    product = productInfo
    product.count = 0
}
product.count += 1
shopInfo[productId] = product
state.cartList[shopid] = shopInfo

如果不写最后一句话state.cartList[shopid] = shopInfo,为什么state里面的cartList没有变化呢

正在回答

1回答

补充锌改变cartList[shopid],不会触发响应式的处理逻辑,所以页面不会渲染。

0 回复 有任何疑惑可以回复我~
  • 提问者 目訫 #1
    就是必须这么写才可以,如果不手动改变state里面的数据,就不会重新渲染页面
    回复 有任何疑惑可以回复我~ 2021-03-19 22:22:55
  • 同样的疑问,没有state.cartList[shopid] = shopInfo这句,后面打印一下console.log(state.cartList[shopId]),是undefined啊,这说明上面一系列的操作并没有对cartList进行赋值呀,应该是有值的呀,这是为啥呢
    回复 有任何疑惑可以回复我~ 2022-06-24 18:50:43
  • addItemToCart: (state, payload) => {
          const { shopId, productId, product } = payload
          console.log(shopId, state.cartList[shopId])
    
          //   let shopInfo = state.cartList[shopId]
          if (!state.cartList[shopId]) {
            state.cartList[shopId] = {}
          }
          //   let productInfo = state.cartList[shopId][productId]
          if (!state.cartList[shopId][productId]) {
            state.cartList[shopId][productId] = product
            state.cartList[shopId][productId].count = 0
          }
          state.cartList[shopId][productId].count += 1
          //   shopInfo[productId] = productInfo
          //   state.cartList[shopId] = shopInfo
          console.log(shopId, state.cartList[shopId])
        }
    要是直接再该对象上做处理,就正常了。使用let引用,处理数据
    
    let shop = {}
    let a = shop
    a.id = 11
    console.log(shop.id) // 11
    有啥不一样了呢,疑问!!
    回复 有任何疑惑可以回复我~ 2022-06-24 18:52:24
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号