郎朗坤
2023-04-27 16:49:54
我在我的本機(jī)反應(yīng)應(yīng)用程序中使用 redux。為了更新一些配置文件數(shù)據(jù),我在我的一個(gè)組件中調(diào)度了一個(gè)動(dòng)作 updateProfile(data)在我的組件中values = { // some Js object values }updateProfile(values)在行動(dòng)創(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 來了解更新的結(jié)果updateProfile(values)setTimeout(()=>{ if(profiles.errMess==null){ setCondition('completed') nav.navigate('some Screen') } else{ setCondition('error') }},3000)因?yàn)槲倚枰獙?dǎo)航到其他屏幕,所以我不能使用 SetTimeOut,因?yàn)樗鼤?huì)不斷地產(chǎn)生延遲,即使更新很快完成,如果更新時(shí)間超過 3 秒,它仍然會(huì)引起頭痛。我想要的是,僅當(dāng)數(shù)據(jù)更新到服務(wù)器時(shí)導(dǎo)航到“某個(gè)屏幕”(如承諾)是的,我可以更新 redux 狀態(tài)中的狀態(tài)值,但我需要在組件級(jí)別實(shí)現(xiàn)它。我是 redux 的新手。請有人幫助我。
1 回答
子衿沉夜
TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
我相信您可以返回 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
})
添加回答
舉報(bào)
0/150
提交
取消
