gpt4 book ai didi

reactjs - Redux 工具包和 createAsyncThunk 不适用于 axios 实例

转载 作者:行者123 更新时间:2023-12-05 01:27:53 26 4
gpt4 key购买 nike

我有一个 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();

值得注意的是,我尝试获取 token ,如果它存在,则在每次请求时将其写入 header 。

因此,我的商店没有初始化(它是空的)。在控制台中我有错误:

  1. 没有为关键“用户”提供reducer
  2. 商店没有有效的 reducer 。确保传递给 combineReducers 的参数是一个值为 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 函数。我分享链接 https://redux.js.org/faq/code-structure#how-can-i-use-the-redux-store-in-non-component-files

关于reactjs - Redux 工具包和 createAsyncThunk 不适用于 axios 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69123984/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com