如何解决在Redux Toolkit中将State与HTMLElement一起用于createSlice
尝试创建一个化简器,其状态包含一个HTMLDivElement类型的键(或任何其他HTMLElement派生类)时,对于似乎是HTMLElement的所有键,我得到了一个Argument of type '...' is not assignable to parameter of type
。
interface ITestEvent {
name: string;
id: string;
ref: HTMLDivElement;
}
interface AddEventPayload {
event: ITestEvent;
}
interface TestEventState {
events: ITestEvent[];
}
const initialState: TestEventState = {
events: [],};
const testSlice = createSlice({
name: 'test',initialState,reducers: {
addEvent(state,action: PayloadAction<AddEventPayload>) {
state.events.push(action.payload.event); // Error here
},},});
下面是说明问题的打字机游乐场链接。
https://typescriptlang.org/play link here
通过createReducer创建减速器时也会发生同样的情况。
这是对TypeScript的某种限制吗?/这是预期的吗?
解决方法
这似乎是immer
类型Draft
的问题。
Draft<typeof initialState>
的结果似乎与其中的原始Event
类型略有不同。
但是,通常不建议这样做,这也可能导致运行时问题,甚至当redux devtools尝试显示该事件时,它们也会崩溃。
仅建议将可序列化的普通对象置于状态: https://redux.js.org/style-guide/style-guide/#do-not-put-non-serializable-values-in-state-or-actions
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。