我正在尝试将现有但旧的项目迁移到更新的技术,特别是标题中提到的技术。我对 Typescript 没有什么经验,对 redux-toolkit 也没有什么经验,而且我习惯了 Firebase v8,但为了模块化而迁移到 v9。
因此,在我的 Firebase 实时数据库中,我有一个用户表,我想从中获取一些信息,我试图通过 createAsyncThunk
来实现此目的来自@reduxjs/toolkit
但到目前为止运气不好。标准操作按照其应有的方式进行处理,因此这绝对是 thunk 造成问题的原因。我附上一些代码:
重击声
import { createAsyncThunk } from "@reduxjs/toolkit";
import { ref, onValue, DataSnapshot, child, DatabaseReference } from "firebase/database";
import { usersDb } from '../Firebase/utils';
import { MyBrandAppUser } from "../Types/MyBrandAppUser";
export const fetchMyBrandAppUser = createAsyncThunk('users/fetchMyBrandAppUser', async (uid: string, thunkAPI) => {
const userEntry: DatabaseReference = child(usersDb, uid);
let theUser: MyBrandAppUser | null = null;
await onValue(userEntry, (snapshot: DataSnapshot) => {
if( snapshot.exists() )
theUser = <MyBrandAppUser>snapshot.val();
else
return null;
},
(err: Error) => {
thunkAPI.rejectWithValue(err)
});
return theUser;
})
恐怕第一部分不会达到我认为应该达到的效果 onValue
不会返回一个 promise ,但这也许是另一个话题了。
商店
import { configureStore, EnhancedStore } from "@reduxjs/toolkit";
import userReducer from '../Features/Auth';
import logger from "redux-logger";
import thunk from "redux-thunk";
import { useDispatch } from 'react-redux'
export const store: EnhancedStore = configureStore({
reducer: {
auth: userReducer,
},
middleware: (getDefaultMiddleware) => getDefaultMiddleware({
serializableCheck: false,
}).concat(logger).concat(thunk)
})
export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();
我的用户切片:
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { User } from "firebase/auth";
import { WritableDraft } from "immer/dist/internal";
import { UserState } from "../../Types/Redux/States";
import { fetchMyBrandAppUser } from "../../API/fetchUser";
import { MyBrandAppUser } from "../../Types/MyBrandAppUser";
const initialState: UserState = {
firebaseUser: undefined,
myBrandAppUser: undefined,
}
const authSlice = createSlice({
name: "users",
initialState,
reducers: {
setFirebaseUser: (state: WritableDraft<UserState>, action:PayloadAction<User | null>) => {
state.firebaseUser = action.payload;
},
},
extraReducers: builder => {
builder.addCase(fetchMyBrandAppUser.fulfilled, (state: WritableDraft<UserState>, action) => {
state.myBrandAppUser = action.payload;
})
}
})
export const { setFirebaseUser } = authSlice.actions;
export default authSlice.reducer;
但是现在如果我尝试调用 dispatch(fetchMyBrandAppUser(userID))
typescript 不允许我这样做,有以下提示:
- 对于常规操作:
Argument of type '{ payload: User | null; type: string; }' is not assignable to parameter of type 'never'.ts(2345)
- 对于 thunk 操作:
Argument of type 'AsyncThunkAction<null, string, {}>' is not assignable to parameter of type 'never'.ts(2345)
我做错了什么?
最佳答案
我通过删除商店中的 EnhancedStore
类型解决了该问题,以供将来引用。
关于reactjs - 在 React 中使用 Firebase 9、Redux Toolkit 和 Typescript 令人头疼。 'dispatch' 不知何故具有类型 'never' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72118986/