在Redux中更新布尔状态时出错



我的state数据:

options: [
{
id: 1,
name: "Sale",
isTrue: false,
},
{
id: 2,
name: "New in",
isTrue: false,
},
],

而且,在减速器中,我有:

closeOptions: (state) => {
state.options  = state.options.map((item) => (item.isTrue = false));
},

但我在state.optionsvscode中的red underline中出现错误。并且,它显示以下错误:

Type 'boolean[]' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>[]'.
Type 'boolean' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>'.ts(2322)

更多,

Unhandled Runtime Error
TypeError: Cannot create property 'isTrue' on boolean 'false'
Source
105 | closeOptions: (state) => {
> 106 |   state.options = state.options.map((item) => (item.isTrue = false));
|                                                          ^
107 | },

如何解决此问题?

TS 中的整个项目

您会收到以下错误:

Type 'boolean[]' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>[]'.
Type 'boolean' is not assignable to type 'WritableDraft<{ id: number; name: string; isTrue: boolean; }>'.ts(2322)

因为当您在closeOptions中使用state.options.map((item) => (item.isTrue = false))时,它返回的是类型为boolean[][false, false],这与类型WritableDraft<{ id: number; name: string; isTrue: boolean; }>[]完全不同。

closeOptions功能更改为:

closeOptions: (state) => {
state.options?.forEach((item) => (item.isTrue = false))
}

如果您正在使用Redux Toolkit,您可以简单地执行:

closeOptions: (state) => {
state.options.forEach((item) => {
item.isTrue = false;
});
},

相关内容

  • 没有找到相关文章

最新更新