如何在NgRx中推送或更新状态



我正在尝试将inputVal值添加到状态中。它只在第一次点击时起作用,在后出现此错误

错误:TypeError: Cannot add property 1, object is not extensible

import { createReducer, on } from '@ngrx/store'
import { addTodo } from '../actions/todo.actions'
export const initialState: any[] = []
let test: any[] = []
const _todoReducer = createReducer(
initialState,
on(addTodo, (state: any, { inputVal }) => {
test.push(inputVal)
state = test
return state
})
)
export function todoReducer(state, action) {
return _todoReducer(state, action)
}

如何在NgRx中推送或更新状态?或者,如果不可能的话,有什么办法呢?

您永远不能在NgRx中修改state,reducer将返回状态的新副本,而不是修改现有副本。所以不能将test添加到state

尝试

const _todoReducer = createReducer(
initialState,
on(addTodo, (state: any, { inputVal }) => {
return [...state,inputVal] // we are creating a new array and this will become the new state.
})
)

例如,在您的组件中,请注入Storeconstructor(private store:Store){..}

商店可以通过this.store.dispatch(addTodo("element"))进行更新

但还有另一个问题。您的存储应该是不可变的,所以您不能在reducer中重用test数组。

const _todoReducer = createReducer(
initialState,
on(addTodo, (state: any, { inputVal }) => {
return [...state, inputVal]
})
)

足够了。

最新更新