如何在发送API请求时显示加载指示符



当请求等待数据时,我想显示一个加载指示器

我正在使用axios发送http请求
和redux作为状态管理

我试图定义一个加载对象,这样每当我调用一个操作时,都会将其设置为true
,但当我获得数据时,它不会变为false

这是我试过的

const INITIAL_STATE ={
loading:false,
success:null,
msg:'',
obj:[]
}

export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case SEND_PHONE:
return {...state,
success:action.payload.success, 
msg:action.payload.msg, 
obj:action.payload.obj
,loading:true};
default:
return state;
}
}

一种方法是使用带有redux thunk的异步操作(https://github.com/reduxjs/redux-thunk)它可以让你在一个动作中调度多次

你的行为可能看起来像这样:

export function fetchSomething() {
return dispatch => {
dispatch({type:FETCH_PENDING})
someApi.getSomeStuff()
.then(response => {
dispatch({type:FETCH_SUCCESSFULL, payload: response.data.results})
return response.data.results
})
.catch(error => {
dispatch({type:FETCH_ERROR, payload: error})
})
}
}

你的减速器看起来像这样,然后

const initialState = {
data: [],
loading: false,
error: null
}
function fetchSomethingReducer(state = initialState, action) {
switch(action.type) {
case FETCH_PENDING:
return {
...state,
loading: true,
error: null
}
case FETCH_SUCCESS:
return {
...state,
loading: false,
data: action.payload
}
case FETCH_ERROR:
return {
...state,
data: [],
loading: false,
error: action.payload
}
default:
return state
}
}

如果您尝试使用redux来实现它,它可能不是直接的,也不是最佳的。我建议看看这个库,它有助于为每个请求执行放置加载指示符,

https://github.com/Lemoncode/react-promise-tracker#readme

在这里,你只需要用这个库提供的一些回调来包装你的axios调用,并将你的加载组件放在适当的位置,一切都将由这个库处理。

另一种方法是可以使用createAsyncThunk,我发现这更容易理解和使用。

使用createAsyncThunk,将为您生成生命周期操作(挂起、完成、拒绝(,您所需要做的就是定义减速器。

以下是从官方网站上截取并稍作修改的react redux:

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { userAPI } from './userAPI'
// First, create the thunk
const fetchUserById = createAsyncThunk(
'users/fetchByIdStatus',
async (userId, thunkAPI) => {
const response = await userAPI.fetchById(userId)
return response.data
}
)
// Then, handle actions in your reducers:
const usersSlice = createSlice({
name: 'users',
initialState: { entities: [], loading: false },
reducers: {
// standard reducer logic, with auto-generated action types per reducer
},
extraReducers: {
// Add reducers for additional action types here, and handle loading state as needed
[fetchUserById.pending]: (state, action) => {
state.loading = true;
},
[fetchUserById.fulfilled]: (state, action) => {
// once createAsyncthunk is 
state.loading = false;
state.entities = state.entities.concat(action.payload)
}
}
})
// define and export this so that you can access the state from your react component. 
export const getLoadingState = (state) => state.users.loading

这样,您就可以在react应用程序中使用useDispatch,如下所示:

dispatch(fetchUserById(123))

为了获得userSlice中的当前冗余状态,您可以使用useSelector,如下所示:

const loadingState = useSelector((state) => getLoadingState (state));

您可以在链接中找到更多详细信息

最新更新