簡體   English   中英

為什么我必須從一個模塊傳播Vuex吸氣劑,而從另一個模塊傳播一個Vuex吸氣劑?

[英]Why do I have to spread a Vuex getter from one module and not one from another module?

我有一個VueX商店,其中有兩個模塊,user.js和商人.js,頂層是index.js。

user.js中的getter是:

重構

  const getters = {
  selectedShippingAddress (state) {
    return state
      .shippingAddresses.find(({ shippingAddressId }) => shippingAddressId 
      === state.selectedShippingAddressId)
     }
    }  

舊版本

   selectedShippingAddress (state) {
    return state
      .shippingAddresses
      .filter(({ shippingAddressId }) => shippingAddressId === state.selectedShippingAddressId)
      .pop()
  }

Merchant.js中的getter是

    merchantAllowedShippingCountries (state) {
      if (state.shippingLocationProfiles) {
        return state.shippingLocationProfiles.split(',')
       } else {
         return []
        }
      }
     }

最后index.js:

   isCountrySupportedByMerchant (state, getters) {

    **// the const userShippingAddress fails **
    const userShippingAddress = getters.selectedShippingAddress

    **// this works with spreading **
    const userShippingAddress = { ...getters.selectedShippingAddress }
    const countriesMerchantShipsTo = getters.countriesAllowedForShipping
    for (const country in countriesMerchantShipsTo) {
      if (userShippingAddress.countryCode === country) {
        return true
      }
    }
    return false
  }

我問這個問題是因為當不使用傳播運算符時,應用程序會失敗以及進行集成測試。

如果數組為空,則兩個版本的user.js(使用find進行重構)和舊版本使用pop()都返回未定義。 我懷疑這與find()使用回調而pop()沒有使用回調有關。 還是這與屬性訪問有關,因為我需要在循環中獲取countryCode?

為什么僅當我從user.js傳播getter時才起作用?

const userShippingAddress = getters.selectedShippingAddress

如果then數組為空,則userShippingAddress將是undefined ,因此userShippingAddress.countryCode將導致錯誤。

但是,當您從user.js { ...getters.selectedShippingAddress }傳播getter時,將是一個像{}這樣的Object,因此userShippingAddress.countryCode將可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM