[英]How to modify state in reduxjs/toolkit with React and TypeScript
[英]How to use object spread reduxjs/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,
};
},
},
});
當我將 state 分配給新的 object 時,我的商店沒有更新。 但是如果我將減速器更改為代碼
state.message = action.payload.message || state.message;
state.open = action.payload.open || state.open;
但這不是很方便。 那么有沒有辦法使用傳播運算符?
在這種情況下,您應該從 function 返回新的 object:
setAlert(state, action: PayloadAction<Partial<AlertState>>) {
return {
...state,
...action.payload,
};
},
您可以在docs中查看更多示例。 另外,請注意以下規則:
您需要確保更改 state 參數或返回新的 state,但不能同時返回兩者。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.