【发布时间】:2021-04-14 08:28:59
【问题描述】:
我遇到了 Redux Toolkit (RTK),并希望实现它提供的更多功能。我的应用程序分派到通过createSlice({}) 创建的reducers 切片(参见createSlice api docs)
到目前为止,这非常有效。我可以轻松地使用内置的 dispatch(action) 和 useSelector(selector) 来调度操作并在我的组件中很好地接收/响应状态变化。
我想使用来自 axios 的异步调用从 API 获取数据并更新存储,因为请求是 A) 开始 B) 完成。
我见过redux-thunk,它似乎完全是为此目的而设计的,但是在一般谷歌搜索之后,新的 RTK 似乎在createSlice() 中不支持它。
以上是目前用切片实现thunk的状态吗?
我在文档中看到您可以将 extraReducers 添加到切片中,但不确定这是否意味着我可以创建更多使用 thunk 的 传统 减速器并让切片实现它们?
总的来说,这是一种误导,因为 RTK 文档显示您可以使用 thunk,但似乎没有提到它不能通过新的 slices api 访问。
来自Redux Tool Kit Middleware的示例
const store = configureStore({
reducer: rootReducer,
middleware: [thunk, logger]
})
我的切片代码显示了异步调用将失败的位置以及其他一些可以工作的示例减速器。
import { getAxiosInstance } from '../../conf/index';
export const slice = createSlice({
name: 'bundles',
initialState: {
bundles: [],
selectedBundle: null,
page: {
page: 0,
totalElements: 0,
size: 20,
totalPages: 0
},
myAsyncResponse: null
},
reducers: {
//Update the state with the new bundles and the Spring Page object.
recievedBundlesFromAPI: (state, bundles) => {
console.log('Getting bundles...');
const springPage = bundles.payload.pageable;
state.bundles = bundles.payload.content;
state.page = {
page: springPage.pageNumber,
size: springPage.pageSize,
totalElements: bundles.payload.totalElements,
totalPages: bundles.payload.totalPages
};
},
//The Bundle selected by the user.
setSelectedBundle: (state, bundle) => {
console.log(`Selected ${bundle} `);
state.selectedBundle = bundle;
},
//I WANT TO USE / DO AN ASYNC FUNCTION HERE...THIS FAILS.
myAsyncInSlice: (state) => {
getAxiosInstance()
.get('/')
.then((ok) => {
state.myAsyncResponse = ok.data;
})
.catch((err) => {
state.myAsyncResponse = 'ERROR';
});
}
}
});
export const selectBundles = (state) => state.bundles.bundles;
export const selectedBundle = (state) => state.bundles.selectBundle;
export const selectPage = (state) => state.bundles.page;
export const { recievedBundlesFromAPI, setSelectedBundle, myAsyncInSlice } = slice.actions;
export default slice.reducer;
我的商店设置(商店配置)。
import { configureStore } from '@reduxjs/toolkit';
import thunk from 'redux-thunk';
import bundlesReducer from '../slices/bundles-slice';
import servicesReducer from '../slices/services-slice';
import menuReducer from '../slices/menu-slice';
import mySliceReducer from '../slices/my-slice';
const store = configureStore({
reducer: {
bundles: bundlesReducer,
services: servicesReducer,
menu: menuReducer,
redirect: mySliceReducer
}
});
export default store;
【问题讨论】:
标签: javascript redux redux-thunk redux-toolkit