郎朗坤
2023-04-27 16:49:54
我在我的本機反應應用程序中使用 redux。為了更新一些配置文件數(shù)據(jù),我在我的一個組件中調(diào)度了一個動作 updateProfile(data)在我的組件中values = { // some Js object values }updateProfile(values)在行動創(chuàng)造者export const updateProfile = (details) =>(dispatch) => {dispatch(profileLoading()) axios.post(SERVERURL,details) //updating the details to the server .then((result)=>{ dispatch(addProfile(result.data[0])) //updating the returned details to redux state }) .catch((err)=>{ dispatch(profileFailed(err.response)) }) }) }export const profileLoading = () => ({ type: ActionTypes.PROFILE_LOADING,})export const addProfile = (profile) => ({ type: ActionTypes.ADD_PROFILE, payload: profile})export const profileFailed = (err) => ({ type: ActionTypes.PROFILE_FAILED, payload: err})配置文件.jsimport * as ActionTypes from './ActionTypes'export const profiles = (state = {isLoading:true,errMess:null,profiles:{ }},action) =>{ switch(action.type){ case ActionTypes.ADD_PROFILE: return {...state, isLoading:false, errMess:null, profiles: action.payload} case ActionTypes.PROFILE_LOADING: return {...state, isLoading:true,errMess:null} case ActionTypes.PROFILE_FAILED: return {...state, isLoading:false,errMess:action.payload, profiles: {}} case ActionTypes.DELETE_PROFILE: return {...state,isLoading:false,errMess:null,profiles:{}} default: return state } }在這一行updateProfile(values)之后,目前正在使用如下所示的 setTimeout 來了解更新的結果updateProfile(values)setTimeout(()=>{ if(profiles.errMess==null){ setCondition('completed') nav.navigate('some Screen') } else{ setCondition('error') }},3000)因為我需要導航到其他屏幕,所以我不能使用 SetTimeOut,因為它會不斷地產(chǎn)生延遲,即使更新很快完成,如果更新時間超過 3 秒,它仍然會引起頭痛。我想要的是,僅當數(shù)據(jù)更新到服務器時導航到“某個屏幕”(如承諾)是的,我可以更新 redux 狀態(tài)中的狀態(tài)值,但我需要在組件級別實現(xiàn)它。我是 redux 的新手。請有人幫助我。
1 回答

子衿沉夜
TA貢獻1828條經(jīng)驗 獲得超3個贊
我相信您可以返回 axios 請求以訪問您調(diào)用它的承諾。
// Action Creator
export const updateProfile = (details) =>(dispatch) => {
? dispatch(profileLoading())
? return axios.post(SERVERURL,details)
? ? .then((result) => {? ? ? ? ? ??
? ? ? dispatch(addProfile(result.data[0]))
? ? }).catch((err) => {
? ? ? dispatch(profileFailed(err.response))
? ? })
? })
}
// Usage
dispatch(updateProfile(values)).then((response) => {
? // handle successful response
}).catch((err) => {
? // handle failure
})
添加回答
舉報
0/150
提交
取消