NgRx 更改嵌套对象的状态

问题描述 投票:0回答:1

我正在学习 NgRx,但我不知道如何更改状态对象内的嵌套值。

import { createReducer, on } from '@ngrx/store';
import { Money } from '@models/money';
import { setMoney } from '@actions/money.actions';

export interface MyState {
    money: Money;
    status: 'pending' | 'loading' | 'error' | 'success';
    error: string;
}

export const initialState: MyState = {
    money: {
        dollars: 10,
        cents: 60,
    },
    status: 'pending',
    error: ''
}

export const myReducer = createReducer(
    initialState,
    on(setMoney, (state, value) => ({
        ...state,
        ...state.money.dollars: value,          // How to access money.dollars and change it's value?
}))

在此示例中,如何更改 MyState.money 的美元或美分值?

谢谢!

angular ngrx
1个回答
0
投票
export const myReducer = createReducer(
    initialState,
    on(setMoney, (state, value) => ({
        ...state,
        money: {...state.money, dollars: value }
    })
)

为了让事情变得更简单,您还可以使用ngrx-immer

© www.soinside.com 2019 - 2024. All rights reserved.