redux已经更新但视图却没有更新?

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_36222440/article/details/85084090

redux已经更新但视图却没有更新?

源代码

addGood(state, { good }) {
      let targetIndex = state.goods.findIndex(item => item.id === good.id)
			console.log("​addGood -> targetIndex", targetIndex)
      if(targetIndex > -1){
        state.goods[targetIndex].num += good.num
      }else{
        state.goods.push(good)
      }
      let goodsTotalNum = 0
      state.goods.forEach(i => {
        goodsTotalNum += i.num
      })
      state.goodsTotalNum = goodsTotalNum
      console.log('​addGood -> state', state)
      return state
    }

正确写法:

   addGood(state, { good }) {
      let stateCopy = {...state}
      let targetIndex = stateCopy.goods.findIndex(item => item.id === good.id)
			console.log("​addGood -> targetIndex", targetIndex)
      if(targetIndex > -1){
        stateCopy.goods[targetIndex].num += good.num
      }else{
        stateCopy.goods.push(good)
      }
      let goodsTotalNum = 0
      stateCopy.goods.forEach(i => {
        goodsTotalNum += i.num
      })
      stateCopy.goodsTotalNum = goodsTotalNum
			console.log("​addGood -> stateCopy", stateCopy)
      console.log('​addGood -> state', state)
      return stateCopy

参考react-redux 更新 state 之后为什么视图没有更新呢?

展开阅读全文

没有更多推荐了,返回首页