如何使用 React 和 TypeScript 在 reduxjs/toolkit 中修改状态
How to modify state in reduxjs/toolkit with React and TypeScript
当我使用 react-redux 时,我更新了这样的状态:
case CartActionTypes.ADD_ITEM:
return {
...state,
cartItems: [...cartItems, { action.payload }];
};
现在我正在使用 reduxjs/toolkit 切片等
我应该以相同的方式更新状态还是使用这样的 .push 方法:
export const cartSlice = createSlice({
name: 'cart',
initialState: initialState,
reducers: {
addItemToCart(state, action) {
state.cartItems.push(action.payload);
},
}
我应该总是return像我以前那样的状态吗
当您在 RTK createSlice
中定义减速器时,状态变为“可变”。因此,您可以使用 push
来更新您的状态而不返回它。
请参阅 Mutating and Returning State 文档
Immer expects that you will either mutate the existing state, or construct a new state value yourself and return it, but not both in the same function! For example, both of these are valid reducers with Immer:
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
todoAdded(state, action) {
// "Mutate" the existing state, no return value needed
state.push(action.payload)
},
todoDeleted(state, action.payload) {
// Construct a new result array immutably and return it
return state.filter(todo => todo.id !== action.payload)
}
}
})
当我使用 react-redux 时,我更新了这样的状态:
case CartActionTypes.ADD_ITEM:
return {
...state,
cartItems: [...cartItems, { action.payload }];
};
现在我正在使用 reduxjs/toolkit 切片等
我应该以相同的方式更新状态还是使用这样的 .push 方法:
export const cartSlice = createSlice({
name: 'cart',
initialState: initialState,
reducers: {
addItemToCart(state, action) {
state.cartItems.push(action.payload);
},
}
我应该总是return像我以前那样的状态吗
当您在 RTK createSlice
中定义减速器时,状态变为“可变”。因此,您可以使用 push
来更新您的状态而不返回它。
请参阅 Mutating and Returning State 文档
Immer expects that you will either mutate the existing state, or construct a new state value yourself and return it, but not both in the same function! For example, both of these are valid reducers with Immer:
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
todoAdded(state, action) {
// "Mutate" the existing state, no return value needed
state.push(action.payload)
},
todoDeleted(state, action.payload) {
// Construct a new result array immutably and return it
return state.filter(todo => todo.id !== action.payload)
}
}
})