我的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.options
和vscode
中的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;
});
},