Redux 工具包和 createAsyncThunk 不适用于 axios 实例
Redux toolkit and createAsyncThunk not working with axios instance
我有一个 react/typescript 项目。我正在使用 redux 来管理状态。
//store.ts
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import { userReducer } from './user';
const RootReducer = combineReducers({
user: userReducer
})
export const store = configureStore({
reducer: RootReducer,
devTools: true,
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
我还有一个userSlice.ts文件:
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { signIn, signUp } from './../../services/api';
import type { UserCredential, UserInitialState } from './types';
const initialState: UserInitialState = {
accessToken: null,
status: 'init',
user: {
id: '',
email: '',
firstName: null,
lastName: null,
isAuthorized: false,
imported: false,
teamId: '',
role: '',
linkedinLink: null,
isReceivingNotifications: false,
avatarKey: null,
loggedInAt: '',
createdAt: '',
updatedAt: '',
deletedAt: null,
},
};
const signUpRequest = createAsyncThunk('user/signUpRequest', async (data: UserCredential) => {
const response = await signUp(data);
return response.data;
});
const signInRequest = createAsyncThunk('user/signInRequest', async (data: UserCredential) => {
const response = await signIn(data);
return response.data;
});
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
logOut() {
return initialState;
},
},
extraReducers: (builder) => {
builder.addCase(signInRequest.pending, (state, action) => {
state.status = 'pending';
});
builder.addCase(signInRequest.fulfilled, (state, action) => {
const { user, accessToken } = action.payload;
return { accessToken, ...user };
});
},
});
export const userSliceActions = {...userSlice.actions};
export default userSlice.reducer;
在此切片中,我使用了 API 中的两个函数(signIn、signUp)
这些函数在下一个文件中描述:
//api.ts
import { UserCredential } from '../store/user/types';
import { AxiosPromise } from 'axios';
import ApiClient from './ApiClient';
export const signUp = (data: UserCredential): AxiosPromise => {
return ApiClient.post('v1/auth/sign_up', { data });
};
export const signIn = (data: UserCredential): AxiosPromise => {
return ApiClient.post('v1/auth/sign_in', { data });
};
上面我使用了 ApiClient.ts 文件中的简单 axios 实例
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { store } from '../store/store';
const baseUrl = 'https://************/api';// valid url
class ApiClient {
private api: AxiosInstance;
constructor() {
this.api = axios.create({
baseURL: baseUrl,
headers: {
'Content-Type': 'application/json',
},
});
this.api.interceptors.request.use((config) => {
const token = store.getState().user.accessToken;
if (token !== null) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
}
post(url: string, { data }: AxiosRequestConfig) {
return this.api.post(url, data);
}
get(url: string) {
return this.api.get(url);
}
put(url: string, { data }: AxiosRequestConfig) {
return this.api.put(url, data);
}
delete(url: string) {
return this.api.delete(url);
}
}
export default new ApiClient();
值得注意的是,我尝试获取令牌,如果它存在,则在每次请求时将其写入 header。
因此,我的商店没有初始化(它是空的)。在控制台中我有错误:
- 没有为键“user”提供缩减程序
- 商店没有有效的减速器。确保传递给 combineReducers 的参数是一个 object 其值是 reducers.
项目结构:
Project structure screenshot
注 1:
如果我删除 userSlice.ts 中的 API 调用,错误就会消失并且商店可以正常工作。在这种形式下,一切都开始了,但我需要在 userSlice 中调用 API...
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import type { UserCredential, UserInitialState } from './types';
const initialState: UserInitialState = {
accessToken: null,
status: 'init',
user: {
id: '',
email: '',
firstName: null,
lastName: null,
isAuthorized: false,
imported: false,
teamId: '',
role: '',
linkedinLink: null,
isReceivingNotifications: false,
avatarKey: null,
loggedInAt: '',
createdAt: '',
updatedAt: '',
deletedAt: null,
},
};
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
logOut() {
return initialState;
},
},
});
export const userSliceActions = { ...userSlice.actions };
export default userSlice.reducer;
我傻了! Redux 文档不建议在非组件文件中导入存储。我引用 “您应该避免将商店直接导入其他代码库文件。虽然它在某些情况下可能有效,但通常最终会导致循环导入依赖性错误。”
这是我的情况,我将商店导入 ApiClient.ts 文件,糟糕。按照文档,我使用了 injectStore 函数。我分享了linkhttps://redux.js.org/faq/code-structure#how-can-i-use-the-redux-store-in-non-component-files
我有一个 react/typescript 项目。我正在使用 redux 来管理状态。
//store.ts
import { configureStore, combineReducers } from '@reduxjs/toolkit';
import { userReducer } from './user';
const RootReducer = combineReducers({
user: userReducer
})
export const store = configureStore({
reducer: RootReducer,
devTools: true,
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
我还有一个userSlice.ts文件:
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { signIn, signUp } from './../../services/api';
import type { UserCredential, UserInitialState } from './types';
const initialState: UserInitialState = {
accessToken: null,
status: 'init',
user: {
id: '',
email: '',
firstName: null,
lastName: null,
isAuthorized: false,
imported: false,
teamId: '',
role: '',
linkedinLink: null,
isReceivingNotifications: false,
avatarKey: null,
loggedInAt: '',
createdAt: '',
updatedAt: '',
deletedAt: null,
},
};
const signUpRequest = createAsyncThunk('user/signUpRequest', async (data: UserCredential) => {
const response = await signUp(data);
return response.data;
});
const signInRequest = createAsyncThunk('user/signInRequest', async (data: UserCredential) => {
const response = await signIn(data);
return response.data;
});
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
logOut() {
return initialState;
},
},
extraReducers: (builder) => {
builder.addCase(signInRequest.pending, (state, action) => {
state.status = 'pending';
});
builder.addCase(signInRequest.fulfilled, (state, action) => {
const { user, accessToken } = action.payload;
return { accessToken, ...user };
});
},
});
export const userSliceActions = {...userSlice.actions};
export default userSlice.reducer;
在此切片中,我使用了 API 中的两个函数(signIn、signUp)
这些函数在下一个文件中描述:
//api.ts
import { UserCredential } from '../store/user/types';
import { AxiosPromise } from 'axios';
import ApiClient from './ApiClient';
export const signUp = (data: UserCredential): AxiosPromise => {
return ApiClient.post('v1/auth/sign_up', { data });
};
export const signIn = (data: UserCredential): AxiosPromise => {
return ApiClient.post('v1/auth/sign_in', { data });
};
上面我使用了 ApiClient.ts 文件中的简单 axios 实例
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { store } from '../store/store';
const baseUrl = 'https://************/api';// valid url
class ApiClient {
private api: AxiosInstance;
constructor() {
this.api = axios.create({
baseURL: baseUrl,
headers: {
'Content-Type': 'application/json',
},
});
this.api.interceptors.request.use((config) => {
const token = store.getState().user.accessToken;
if (token !== null) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
}
post(url: string, { data }: AxiosRequestConfig) {
return this.api.post(url, data);
}
get(url: string) {
return this.api.get(url);
}
put(url: string, { data }: AxiosRequestConfig) {
return this.api.put(url, data);
}
delete(url: string) {
return this.api.delete(url);
}
}
export default new ApiClient();
值得注意的是,我尝试获取令牌,如果它存在,则在每次请求时将其写入 header。
因此,我的商店没有初始化(它是空的)。在控制台中我有错误:
- 没有为键“user”提供缩减程序
- 商店没有有效的减速器。确保传递给 combineReducers 的参数是一个 object 其值是 reducers.
项目结构:
Project structure screenshot
注 1: 如果我删除 userSlice.ts 中的 API 调用,错误就会消失并且商店可以正常工作。在这种形式下,一切都开始了,但我需要在 userSlice 中调用 API...
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import type { UserCredential, UserInitialState } from './types';
const initialState: UserInitialState = {
accessToken: null,
status: 'init',
user: {
id: '',
email: '',
firstName: null,
lastName: null,
isAuthorized: false,
imported: false,
teamId: '',
role: '',
linkedinLink: null,
isReceivingNotifications: false,
avatarKey: null,
loggedInAt: '',
createdAt: '',
updatedAt: '',
deletedAt: null,
},
};
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
logOut() {
return initialState;
},
},
});
export const userSliceActions = { ...userSlice.actions };
export default userSlice.reducer;
我傻了! Redux 文档不建议在非组件文件中导入存储。我引用 “您应该避免将商店直接导入其他代码库文件。虽然它在某些情况下可能有效,但通常最终会导致循环导入依赖性错误。” 这是我的情况,我将商店导入 ApiClient.ts 文件,糟糕。按照文档,我使用了 injectStore 函数。我分享了linkhttps://redux.js.org/faq/code-structure#how-can-i-use-the-redux-store-in-non-component-files