ngxs - 未调用选择器订阅
问题描述
有人可以解释何时selector
调用订阅吗?我之前的理解是,每当 reducer 更改state
(创建了一些差异)时,selector
就会被调用。但是在下面的代码中,它没有发生。
当我分派SaveVersionSuccess
. 在减速器中,我state.version.versions[0].updated_fields.workflow
从更改true
为false
。
有人可以解释为什么吗?堆栈闪电战
@Select(state => state.version.versions) version$: Observable<any[]>;
ngOnInit(): void {
this.version$.subscribe((versions) => {//line A
alert()
});
}
test(){
this.store.dispatch([
new SaveVersionSuccess({bot:null, version:{id: 1, updated_fields:{'workflow':false}}})
]);
减速器
@Action(SaveVersionSuccess)
SaveVersionSuccess({patchState, setState, getState, dispatch,}: StateContext<ICodeInputState>, {payload}: SaveVersionSuccess) {
let state = getState();
let index = state.versions.findIndex((version) => version.id === payload.version.id);
let index_pristine = state.versions_pristine.findIndex((version) => version.id === payload.version.id);
state.versions[index] = {
...payload.version
};
state.versions_pristine[index_pristine] = {
...payload.version
};
patchState({...state});
}
初始状态
const codeInputState: ICodeInputState = {
versions: [{id: 1, updated_fields:{'workflow':true}}],
versions_pristine: [{id: 1, updated_fields:{'workflow':true}}]
};
解决方案
正如评论所暗示的那样,在修补状态时,它看起来像是一个不变性问题,原来是在修改现有状态而不是修补新状态。
我在您的 StackBlitz 上尝试了此版本,似乎可以按我认为的那样工作:
@Action(SaveVersionSuccess)
SaveVersionSuccess({patchState, setState, getState, dispatch,}: StateContext<ICodeInputState>, {payload}: SaveVersionSuccess) {
let state = getState();
let index = state.versions.findIndex((version) => version.id === payload.version.id);
let index_pristine = state.versions_pristine.findIndex((version) => version.id === payload.version.id);
// Create a new versions array
const versions = [...state.versions];
// Patch the value at the required index
versions[index] = payload.version;
// Create a new versions_pristine array
const versions_pristine = [...state.versions_pristine];
// Patch the value at the required index
versions_pristine[index_pristine] = payload.version;
// Patch the state with the new arrays
patchState({
versions: versions,
versions_pristine: versions_pristine
});
}
推荐阅读
- php - 无法使用php访问上传文件输入
- three.js - Three.js InstancedMesh:更新实例矩阵后不改变着色器
- javascript - 使用 Mongoose 中间件修改请求正文
- machine-learning - 使用 KNeighborsClassifier 时,使用 weights="distance" 的动机是什么
- android - 如何使用接口调用视图寻呼机持有的片段内的方法表单?
- hadoop - 无法规范化地址 localhost/
:2222 因为它无法解析 - mysql - Scala 读取 Kafka 主题并写入 MySQL 表
- c - 当 pow() 在 main() 中而不是当 pow() 在函数中时,C 文件在没有 -lm 的情况下编译
- c# - Unity2D 使用协程跟踪玩家何时转动?
- r - 如何计算字符串中的元素个数