【发布时间】: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