angular - 以编程方式访问 NGRX 状态中的值
问题描述
我有一个 NGRX 状态设置,它是一个值的对象。值键是带有布尔值的数字 (1-5)。
状态.ts
export interface State {
1: boolean;
2: boolean;
3: boolean;
4: boolean;
5: boolean;
}
export const initialState: State = {
1: true,
2: true,
3: true,
4: true,
5: true,
}
我还有一个通过它传递对象编号值的操作。所以在我的减速器中,我正在获取数值,在对象中找到该值,然后切换布尔值。但是,我遇到了一个问题,即我无法在减速器功能中选择对象键,而无需实际输入物理数字。
动作.ts
export const changeButtonState = createAction(
'[Bingo Actions] Change Button State',
(payload: number) => ({payload}),
);
减速器.ts
export const reducer = createReducer(
initialState,
on(BingoActions.changeButtonState, (state, action) => {
return {
...state,
action.payload: !state[action.payload],
};
})
);
如何在无需在 reducer 函数中物理输入数字的情况下访问对象的数字值?
解决方案
对象键的计算属性名称 - https://ui.dev/computed-property-names/
export const stateKeys = {
one: 1,
two: 2,
...
export interface State {
[stateKeys.one]: boolean;
[stateKeys.two]: boolean;
...
然后要在 reducer 中使用计算名称访问属性,语法是:
state[stateKeys.one]
推荐阅读
- python - ValueError:无法分配“'656937'”:“LeaveTracker.emp_id”必须是“Employee”实例
- git - 尝试恢复到以前的提交后无法推送,Git
- java - 在java mongodb中按数组长度排序
- flutter - Flutter - 保存在 List 中时 MaterialButton 不会改变
- foreach - 从使用 forEach 的异步函数获取返回值
- ios - 计算 UITableView 预期高度
- ios - iOS13 立即检查互联网连接
- laravel - laravel上的图片上传无法在线使用
- php - 无法从 PHP 运行 python 代码 - 无输出
- powershell - 在这个程序中,如何检查输入值是否在 -9 到 0 到 9 范围内的任何整数或小数范围内?