如何在 NgRx 中推送或更新状态?
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 将 return 状态的新副本,而不是修改现有状态。所以你不能将 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){..}
可以通过 this.store.dispatch(addTodo("element"))
更新商店
但是还有一个问题。您的商店应该是不可变的,因此您不能在 reducer 中重用 test
数组。
const _todoReducer = createReducer(
initialState,
on(addTodo, (state: any, { inputVal }) => {
return [...state, inputVal]
})
)
够了。
我正在尝试将 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 将 return 状态的新副本,而不是修改现有状态。所以你不能将 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){..}
可以通过 this.store.dispatch(addTodo("element"))
但是还有一个问题。您的商店应该是不可变的,因此您不能在 reducer 中重用 test
数组。
const _todoReducer = createReducer(
initialState,
on(addTodo, (state: any, { inputVal }) => {
return [...state, inputVal]
})
)
够了。