[英]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.