我一直在尝试使用 Redux 工具包进行身份验证刷新令牌调用,但在安装所有修复程序后,它现在仍然能够读取错误消息。
设置 axios 实例:
export const axiosInstance = axios.create({
baseURL: REACT_APP_API_URL,
});
Run Code Online (Sandbox Code Playgroud)
进行API调用:
export const refreshAccessAndRefreshTokens = async () => {
const response = await axiosInstance({
method: 'post',
url: '/refresh-tokens',
withCredentials: true,
});
return response;
};
Run Code Online (Sandbox Code Playgroud)
thunk函数:
// GET ACCESS TOKEN USING REFRESH TOKEN
export const refreshTokens = createAsyncThunk(
'auth/refreshTokens',
async ({ rejectWithValue }) => {
try {
const response = await refreshAccessAndRefreshTokens();
return response.data;
} catch (error) {
console.log('error', error);
console.log('data', error.response.data);
console.log('message', error.response.data.message);
return rejectWithValue(error.response.data.message);
} …Run Code Online (Sandbox Code Playgroud) 在我的fullfilledi 中得到的响应为undefined。有人请帮忙吗?
代码 :
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
const fetchPost = createAsyncThunk('fetch/post', async (params: string) => {
try {
const { data } = await axios.get('https://registry.npmjs.org/-/v1/search', { params: { text: params } })
data.objects.map((result: any) => {
console.log('result', result)//getting result
return result.package.name;
});
} catch (err: any) {
return err?.response;
}
})
interface RepositoriesState {
loading: boolean;
error: string | null;
data: string[];
}
const initialRepoState:RepositoriesState = {
loading: …Run Code Online (Sandbox Code Playgroud) 通常在 thunk 中你最终会调用其他操作:
\n\nconst startRecipe = {type: "startRecipe"}\n\nconst reducer = (state, action) => {\n if (action.type === "startRecipe") { \n state.mode = AppMode.CookRecipe\n }\n}\n\nconst getRecipeFromUrl = () => async dispatch => {\n const res = await Parser.getRecipeFromUrl(url)\n dispatch(startRecipe)\n}\nRun Code Online (Sandbox Code Playgroud)\n\n在 redux 工具包中createAsyncThunk,这并不是那么简单。事实上,您可以通过以下操作来改变状态extraReducers:
export const getRecipeFromUrl = createAsyncThunk(\'getRecipeFromUrl\',\n async (url: string): Promise<RecipeJSON> => await Parser.getRecipeFromUrl(url)\n)\n\nconst appStateSlice = createSlice({\n name: \'app\',\n initialState: initialAppState,\n reducers: {},\n extraReducers: ({ addCase }) => {\n addCase(getRecipeFromUrl.fulfilled, (state) => {\n state.mode …Run Code Online (Sandbox Code Playgroud) 我是初学者,不知道 createSlice 和 createReducer 有没有区别。
我应该选择哪个?
其次,我今天看了一个教程。这家伙刚刚制作了一个 store.js 文件和一个 userslice.js 文件。很简单。
但是他使它与 redux 文档有点不同。他在 userSlice.js 的末尾导出了三个 CONST,而不是文档中的两个。(我已经发表评论了)如果我将 state.user.user 更改为 state.user.wtf ......我会在一段时间后运行错误,因为某些组件不再访问用户对象了。
用户切片
import { createSlice } from '@reduxjs/toolkit';
export const userSlice = createSlice({
name: "user",
initialState: {
user: null,
},
reducers: {
login: (state, action) => {
state.user = action.payload;
},
logout: (state) => {
state.user = null;
},
},
});
export const { login, logout } = userSlice.actions;
export const selectUser = (state) => state.user.user; // What is that …Run Code Online (Sandbox Code Playgroud) 我有一个关于使用Redux ToolkitcreateEntityAdapter的问题。
我有一个应用程序,它使用AG 网格库的主/详细信息功能来显示包和包详细信息。应用程序首先加载包数据,然后在扩展每个包行时获取详细数据。
我想用createEntityAdapter规范化的方式管理数据,但我无法弄清楚如何处理详细网格的动态特性。现在,我有一个减速器切片,每次加载一组详细记录时都会创建一个新属性。属性键是id父包行的,因此在加载data包数据和详细数据后,我的切片最终看起来像这样:123
{
PACKAGES: [{ id: 123, ...otherData }, { id: 124, ...otherData }],
'123': [{ id: 456, ...otherDetailData }],
}
Run Code Online (Sandbox Code Playgroud)
当用户展开124包行时,会获取该包的详细数据,然后如下所示:
{
PACKAGES: [{ id: 123, ...otherData }, { id: 124, ...otherData }],
'123': [{ id: 456, ...otherDetailData }],
'124': [{ id: 457, ...otherDetailData }],
}
Run Code Online (Sandbox Code Playgroud)
因此,虽然我可以将数据分解PACKAGES到其自己的实体适配器中,但我无法对详细网格执行相同的操作,因为我事先并不了解每个网格。
我想我和这个问题的人有类似的问题。
我考虑过将所有详细数据存储在单个实体适配器中,并由父级维护另一个索引id,但这似乎很难保持同步。
有任何想法吗?这种情况下的最佳实践是什么?
设置中间件时出现以下错误。使用 Redux observable/Redux 工具包。关于为什么会发生这种情况有任何意见吗?
遵循以下回购协议设置。 https://github.com/beast911/react-redux-observables-typescript
import systemReducer, {
getInfoStart,
getInfoSuccess,
getInfoFailed,
addInfoStart,
addInfoSuccess,
addInfoFailed,
editInfoStart,
editInfoSuccess,
editInfoFailed,
deleteInfoStart,
deleteInfoSuccess,
deleteInfoFailed,
completeInfoStart,
completeInfoSuccess,
completeInfoFailed,
} from "./system/slice";
import {
combineReducers,
configureStore,
getDefaultMiddleware,
} from "@reduxjs/toolkit";
import { createBrowserHistory } from "history";
import { combineEpics, createEpicMiddleware } from "redux-observable";
import {
getInfoEpic,
addInfoEpic,
completeInfoEpic,
deleteInfoEpic,
editInfoEpic,
} from "./system/epics";
import { ActionType } from "typesafe-actions";
import {
connectRouter,
routerMiddleware,
RouterState,
} from "connected-react-router";
type SystemActionsWithPayload =
| typeof getInfoStart
| typeof …Run Code Online (Sandbox Code Playgroud) Error:
index.js:1 A non-serializable value was detected in an action, in the path:
payload.config.transformRequest.0.
Value: ƒ
transformRequest(data, headers) {
Run Code Online (Sandbox Code Playgroud)normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.i…
Slice:
export const getProducts = createAsyncThunk(
'products/getProducts',
async() => {
const res = await axios.get('http://localhost:5000/products/view-products', {withCredentials: true});
return res;
}
)
const getProductsSlice = createSlice({
name : 'products',
initialState : {
list : [],
status : null
},
extraReducers : {
[getProducts.pending] : (state) => {
state.status = 'loading'
}, …Run Code Online (Sandbox Code Playgroud) 我的商店是这样的:
export default configureStore({
reducer: {
sequencer: sequencerReducer,
editMode: editModeReducer,
tone: toneReducer,
app: appReducer,
},
middleware: (getDefaultMiddleware) => {
getDefaultMiddleware({ immutableCheck: false });
},
});
Run Code Online (Sandbox Code Playgroud)
我有一个工作thunk,但我需要这个immutableCheck: false配置。一旦设置,它似乎会覆盖默认的中间件,并且 thunk 不再工作。这是我的想法:
export const modCell = (step, noteOn) => (dispatch, getState) => {
const selectedSound = getState().editMode.selectedSound;
dispatch(sequencerSlice.actions.toggleCell({ step, selectedSound }));
};
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
Error: Actions must be plain objects. Use custom middleware for async actions.
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
现在我已经有了这些用于上传 thunk 生命周期的操作。
type UPLOAD_START = PayloadAction<void>
type UPLOAD_SUCCESS = PayloadAction<{ src: string, sizeKb: number }>
type UPLOAD_FAILURE = PayloadAction<{ error: string }>
Run Code Online (Sandbox Code Playgroud)
我想将它转换为createAsyncThunk调用,假设它会减少代码。但是会吗?
从https://redux-toolkit.js.org/api/createAsyncThunk上的示例来看,它应该是这样的:
const uploadThumbnail = createAsyncThunk(
'mySlice/uploadThumbnail',
async (file: File, thunkAPI) => {
const response = await uploadAPI.upload(file) as API_RESPONSE
return response.data // IS THIS THE payload FOR THE fulfilled ACTION ?
}
)
Run Code Online (Sandbox Code Playgroud)
这是我将如何处理生命周期操作?
const usersSlice = createSlice({
name: 'mySlice',
initialState: // SOME INITIAL STATE,
reducers: {
// standard reducer logic, with …Run Code Online (Sandbox Code Playgroud) redux-toolkit ×10
redux ×6
redux-thunk ×5
reactjs ×4
react-redux ×2
typescript ×2
express ×1
javascript ×1
middleware ×1
react-native ×1
thunk ×1