我正在尝试从动作中访问状态信息。状态是具有ID属性的对象数组。
在检查动作中的变量state.devices
时,我只会看到以下内容:
下面是一个简短的示例,举例说明了各种尝试。抱歉,它无法运行。
const state = {
devices: {}
};
const getters = {
devices: state => state.devices || {}
};
const actions = {
[DEVICE_EVENT_ACTION]: ({ commit }, event) => {
// Attempt 0: exits prematurely
let storedDevice0 = getters
.devices(state)
.find(d => d.deviceId === event.deviceId);
// Attempt 1: exits prematurely
let storedDevice1 = JSON.parse(JSON.stringify(state.device)).find(
x => x.deviceId === event.deviceId
);
// Attempt 2: exits prematurely
let storedDevice2 = state.devices.find(x => x.deviceId === event.deviceId);
// Attempt 3: exits prematurely
let storedDevice3;
for (let d in state.devices) {
if (state.devices[d].deviceId === event.deviceId) {
storedDevice3 = state.devices[d];
}
}
console.log(storedDevice0); // nothing
console.log(storedDevice1); // nothing
console.log(storedDevice2); // nothing
console.log(storedDevice3); // nothing
commit(DEVICE_UPDATED, event);
}
};
const mutations = {
[DEVICE_UPDATED](state, event) {
// Attempt 0
let storedDevice0 = getters
.devices(state)
.find(d => d.deviceId === event.deviceId);
// Attempt 1
let storedDevice1 = JSON.parse(JSON.stringify(state.devices)).find(
x => x.deviceId === event.deviceId
);
// Attempt 2:
let storedDevice2 = state.devices.find(x => x.deviceId === event.deviceId);
// Attempt 3
let storedDevice3;
for (let d in state.devices) {
if (state.devices[d].deviceId === event.deviceId) {
storedDevice3 = state.devices[d];
}
}
console.log(storedDevice0); // works
console.log(storedDevice1); // works
console.log(storedDevice2); // works
console.log(storedDevice3); // works
}
};
我在文档中找不到任何提及此内容的信息。为什么会有所不同,以及如何在操作中访问该状态列表属性?这种选择背后的逻辑是,我的动作可以更具体,这称为更通用的“设备更新”增变器,它使我可以记录状态对象中不存在但确实存在的相关数据并通知用户在商店的device
数组中。