[英]How to push or update state in 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.
})
)
例如,在你的组件中,请注入 Store constructor(private store:Store){..}
Store 可以通过this.store.dispatch(addTodo("element"))
但还有另一个问题。 您的商店应该是不可变的,因此您不能在减速器中重用test
数组。
const _todoReducer = createReducer(
initialState,
on(addTodo, (state: any, { inputVal }) => {
return [...state, inputVal]
})
)
足够。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.