Kos*_*sko 6 reactjs redux redux-toolkit
我正在尝试将 @reduxjs/toolkit 实现到我的项目中,目前我面临使用扩展运算符的问题
const initialState: AlertState = {
message: '',
open: false,
type: 'success',
};
const alertReducer = createSlice({
name: 'alert',
initialState,
reducers: {
setAlert(state, action: PayloadAction<Partial<AlertState>>) {
state = {
...state,
...action.payload,
};
},
},
});
Run Code Online (Sandbox Code Playgroud)
当我将状态分配给新对象时,我的商店不会更新。但是如果我将减速器更改为代码
state.message = action.payload.message || state.message;
state.open = action.payload.open || state.open;
Run Code Online (Sandbox Code Playgroud)
但这不太方便。那么有没有办法使用扩展运算符呢?
fal*_*sky 13
在这种情况下,您应该从函数返回新对象:
setAlert(state, action: PayloadAction<Partial<AlertState>>) {
return {
...state,
...action.payload,
};
},
Run Code Online (Sandbox Code Playgroud)
您可以在文档中查看更多示例。另外,请注意以下规则:
您需要确保要么改变状态参数,要么返回一个新状态,但不能两者兼而有之。
| 归档时间: |
|
| 查看次数: |
2853 次 |
| 最近记录: |