reactjs - 如何使用对象传播 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.message = action.payload.message || state.message;
state.open = action.payload.open || state.open;
但这不是很方便。那么有没有办法使用传播运算符?
解决方案
在这种情况下,您应该从函数中返回新对象:
setAlert(state, action: PayloadAction<Partial<AlertState>>) {
return {
...state,
...action.payload,
};
},
您可以在docs中查看更多示例。另外,请注意以下规则:
您需要确保改变状态参数或返回新状态,但不能同时改变两者。
推荐阅读
- ios - iOS 上的 Google 跟踪代码管理器用途
- google-data-studio - 如何在 Data Studio 中集成 FileMaker (ODBC)?
- c++ - 模板类 + 委托构造函数 = 未初始化的字段?(整洁)
- sql - 创建表时出现 Sql 错误 - Firebird
- c# - 将 EF 6 WPF 应用程序转换为 EF Core,从工作查询中获取空异常
- c# - 将 C#-Client 连接到 C++ Server 时出现 System.Net.Sockets.SocketException (0x80004005)
- android - 在 Android Studio 中使用 Kotlin 将 URI 的内容转换为 ByteArray
- javascript - Angular 7 中的 ApiService.ts 中的用户 JSON.parse()
- visual-studio - VS2019:如何禁用滚动条中的错误导航器?
- python - 无法使基于布尔语句的 while 循环正常运行