Javascript 为什么我必须从一个模块传播Vuex getter,而不是从另一个模块传播Vuex getter?
我有一个VueX商店,有两个模块,user.js和merchant.js,顶层是index.js user.js中的getter是: 重构Javascript 为什么我必须从一个模块传播Vuex getter,而不是从另一个模块传播Vuex getter?,javascript,vue.js,cypress,Javascript,Vue.js,Cypress,我有一个VueX商店,有两个模块,user.js和merchant.js,顶层是index.js user.js中的getter是: 重构 const getters = { selectedShippingAddress (state) { return state .shippingAddresses.find(({ shippingAddressId }) => shippingAddressId === state.selectedShip
const getters = {
selectedShippingAddress (state) {
return state
.shippingAddresses.find(({ shippingAddressId }) => shippingAddressId
=== state.selectedShippingAddressId)
}
}
旧版本
selectedShippingAddress (state) {
return state
.shippingAddresses
.filter(({ shippingAddressId }) => shippingAddressId === state.selectedShippingAddressId)
.pop()
}
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
}
我问这个问题是因为应用程序失败,并且在不使用spread操作符时集成测试失败
如果数组为空,则user.js的两个版本、使用find的重构版本和使用pop()的旧版本都返回undefined。我怀疑这与find()使用回调而pop()不使用回调有关。或者这是因为我需要在循环中获取countryCode而涉及到属性访问
为什么只有当我从user.js传播getter时,这才起作用
const userShippingAddress = getters.selectedShippingAddress
当then数组为空时,userShippingAddress
将是未定义的
,因此userShippingAddress.countryCode
将导致错误
但是,当您从user.js传播getter时,
{…getters.selectedShippingAddress}
将是一个对象,像这样的{}
,因此userShippingAddress.countryCode
可以正常工作。在等待回答时,我怀疑这是关于属性访问的。感谢您的澄清。