我在我的本机应用程序中使用redux。为了更新一些个人资料数据,我在我的一个组件中调度了一个动作updateProfile(data)
在我的组件中
values = { // some Js object values }
updateProfile(values)
在行动中
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
})
profile.js
import * 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,因为即使更新快速完成,它也会不断产生延迟,并且如果更新花费3秒钟以上,仍然会令人头疼。我想要的是,仅当数据更新到服务器时才导航到“某个屏幕”(例如Promise)是的,我可以在redux状态下更新状态值,但我需要在组件级别上实现它。是Redux的新手。请有人帮我。
我相信您可以返回axios请求,以便在您调用它的位置访问promise。
您可以在此处看到有关您面临的相同挑战的讨论:https : //github.com/reduxjs/redux-thunk/issues/61
// 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
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句