在我的组件中,我必须进行API调用。我利用Redux来存储API调用的结果。现在,在Redux中,我使用Thunk中间件来调度操作。我的Redux代码如下:
API呼叫:
export const thunkFetchOrders = (
query = "",
offset = 0,
limit = 10,
filters = {}
): AppThunk<Promise<any>> => async dispatch => {
if (offset === 0) {
dispatch(
resetOrders()
)
}
const requestParams = {
offset,
limit
}
if (query != "") {
Object.assign(requestParams, queryString.parse(query));
}
return axios.get(`/orders`, {params: requestParams})
.then(async (response) => {
dispatch(
fetchOrders(
response.data,
limit,
offset,
filters
)
)
})
.catch((err) => dispatch(thunkFetchError(err)))
}
减速器:
import {
OrdersState,
OrdersActionTypes,
FETCH_ORDERS,
RESET_ORDERS
} from './types';
const initalState: OrdersState = {
items: [],
totalCount: -1
}
export function ordersReducer(
state = initalState,
action: OrdersActionTypes
): OrdersState {
switch(action.type) {
case FETCH_ORDERS:
return {
...state,
items: action.payload.items,
totalCount: action.payload.total
}
case RESET_ORDERS:
return {
...initalState
}
default:
return state;
}
}
操作:
import {
FETCH_ORDERS,
RESET_ORDERS
} from './types';
export function fetchOrders(orders: {}, limit: number, offset: number, filters: {}){
return {
type: FETCH_ORDERS,
payload: orders,
limit: limit,
offset: offset,
filters: {}
}
}
export function resetOrders(){
return {
type: RESET_ORDERS
}
}
类型:
//CONSTANTS
export const FETCH_ORDERS = 'FETCH_ORDERS';
export const RESET_ORDERS = 'RESET_ORDERS';
//TYPES
export interface OrdersState {
items: any[],
totalCount: number
}
interface FetchOrdersAction {
type: typeof FETCH_ORDERS,
payload: {
items: any[],
total: number
},
limit: number,
offset: number,
filters: {}
}
interface ResetOrdersAction {
type: typeof RESET_ORDERS
}
export type OrdersActionTypes = FetchOrdersAction | ResetOrdersAction;
现在在组件中,我将状态映射并分配给道具,这样我就可以从API提取数据,如下所示:
const mapState = (state : RootState) => ({
orders: state.orders.items,
debtor: state.debtor.debtor,
totalCount: state.orders.totalCount
})
const mapDispatch = (dispatch: ThunkDispatch<RootState, void, Action>) => {
return {
fetchOrders: () => dispatch(thunkFetchOrders()),
fetchDebtor: (uuid: string) => dispatch(thunkFetchDebtor(uuid)),
fetchCredentials: () => dispatch(thunkFetchCredentials())
};
}
//const connector = connect(mapState, mapDispatch)(Root);
const connector = connect(mapState, mapDispatch);
在我的组件中,我在useEffect挂钩中进行API调用,并具有一个依赖于redux状态才能实际显示项目的Flatlist。但是,这仅在第二个渲染上显示项目,这是有道理的,因为调用是异步的。我的问题现在是使组件等待API调用完成的一种干净方法。