[英]How to push or update state in NgRx?
I'm trying to add the inputVal value to the state.我正在尝试将 inputVal 值添加到状态。 It only works on the first click, and getting this error after它仅适用于第一次点击,并在之后出现此错误
Error: TypeError: Cannot add property 1, object is not extensible
错误:类型错误: 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)
}
How do I push or update state in NgRx?如何在 NgRx 中推送或更新状态? or if its not possible, what's the work around for it?或者如果它不可能,它的解决方法是什么?
You can never modify a state
in NgRx
, the reducer will return a new copy of state rather than modifying the existing one.你永远不能修改NgRx
的state
,reducer 将返回一个新的状态副本而不是修改现有的状态。 So you can't add test
to state
所以你不能将test
添加到state
try尝试
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.
})
)
For example, in your component please inject Store constructor(private store:Store){..}
例如,在你的组件中,请注入 Store constructor(private store:Store){..}
Store can be updated via this.store.dispatch(addTodo("element"))
Store 可以通过this.store.dispatch(addTodo("element"))
but there is another problem.但还有另一个问题。 Your store should be immutable, so you cannot reuse test
array in reducer.您的商店应该是不可变的,因此您不能在减速器中重用test
数组。
const _todoReducer = createReducer(
initialState,
on(addTodo, (state: any, { inputVal }) => {
return [...state, inputVal]
})
)
is enough.足够。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.