【问题标题】:Why do I have to spread a Vuex getter from one module and not one from another module?为什么我必须从一个模块传播 Vuex getter 而不是从另一个模块传播?
【发布时间】:2019-04-19 15:01:13
【问题描述】:

我有一个 VueX 商店,有两个模块,user.js 和 Mercer.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() 的旧版本,如果数组为空,都返回 undefined。我怀疑这与 find() 使用回调而 pop() 没有的事实有关。或者这与属性访问有关,因为我需要在循环中获取 countryCode?​​p>

为什么只有当我从 user.js 传播 getter 时这才有效?

【问题讨论】:

    标签: javascript vue.js cypress


    【解决方案1】:
    const userShippingAddress = getters.selectedShippingAddress
    

    当 then 数组为空时,那么userShippingAddress 将是undefined,所以userShippingAddress.countryCode 会导致错误。

    但是,当您从 user.js 传播 getter 时,{ ...getters.selectedShippingAddress } 将是一个对象,例如 {},因此 userShippingAddress.countryCode 可以正常工作。

    【讨论】:

    • 当我在等待答案时,我怀疑它与财产访问有关。感谢您的澄清。
    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 2017-07-25
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多