我发现试图将状态传递到entityAdapter CRUD函数时出现TS类型错误
实时沙箱(错误行已注释掉):
https://codesandbox.io/s/createentityadapter-demo-5rvl4
创建图书适配器
const booksAdapter = createEntityAdapter<Book>({
selectId: (book) => book.bookId,
sortComparer: (a, b) => a.title.localeCompare(b.title)
});...create存储片并配置存储区
const booksSlice = createSlice({
name: "books",
initialState: booksAdapter.getInitialState(),
reducers: {
// Can pass adapter functions directly as case reducers. Because we're passing this
// as a value, `createSlice` will auto-generate the `bookAdded` action type / creator
bookAdded: booksAdapter.addOne,
bookRemoved: booksAdapter.removeOne,
bookUpdated: booksAdapter.updateOne,
booksReceived(state, action) {
// Or, call them as "mutating" helpers in a case reducer
booksAdapter.setAll(state, action.payload.books);
}
}
});
export const store = configureStore({
reducer: {
books: booksSlice.reducer
}
});...dispatch的工作方式与预期一致
store.dispatch(bookAdded({ bookId: 1, title: "title 1" }));
store.dispatch(bookAdded({ bookId: 2, title: "title 2" }));
store.dispatch(bookAdded({ bookId: 3, title: "title 3" }));但是当我检索存储状态并尝试在对adapter.addOne的命令式调用中使用它时(即不是通过reducer),我得到了一个错误
let storeState = store.getState();
console.log("storeState", storeState, typeof storeState);
// booksAdapter.addOne(storeState, { id: 4, title: "title 4" });storeState的console.log看起来像一个有效的对象...
storeState
{books: Object}
books: Object
ids: Array(3)
0: 1
1: 2
2: 3
entities: Object
1: Object
2: Object
3: Object
object 但是这行(被注释掉了)
booksAdapter.addOne(storeState, { id: 4, title: "title 4" });导致TS错误的结果:
let storeState: {
books: EntityState<Book>;
}
No overload matches this call.
Overload 1 of 2, '(state: EntityState<Book>, entity: Book): EntityState<Book>', gave the following error.
Argument of type '{ books: EntityState<Book>; }' is not assignable to parameter of type 'EntityState<Book>'.我不明白为什么会有不匹配,因为我直接传入了商店。
我已经在JS中尝试过了,当然没有类型问题,而且还能正常工作。我的问题是:如果不是store.getState()的结果,那么在使用TS时传递给CRUD函数的正确状态对象是什么?
发布于 2021-09-22 14:48:05
数据在storeState.books中,而不是在storeState中。
因此,您需要调用
booksAdapter.addOne(storeState.books, { id: 4, title: "title 4" });请注意,这不会修改您的状态,但只会给您提供所述状态的修改副本。您只能通过操作调度修改您的状态。
https://stackoverflow.com/questions/69283360
复制相似问题