私のreactNativeアプリケーションでreduxを使用しています。一部のプロファイルデータを更新するために、コンポーネントの1つでアクションupdateProfile(data)をディスパッチしています
私のコンポーネントで
values = { // some Js object values }
updateProfile(values)
actionCreatorで
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)
他の画面に移動する必要があるため、更新がすぐに完了しても常に遅延が発生し、更新に3秒以上かかると頭痛の種になるため、SetTimeOutを使用できません。私が欲しいのは、データがサーバーに更新されたときにのみ「いくつかの画面」に移動することです(promiseのように)はい私はredux状態で状態値を更新できますが、コンポーネントレベルでそれを達成する必要があります。reduxは初めてです。誰か助けてください。
私はあなたがそれを呼ぶところの約束にアクセスするためにaxiosリクエストを返すことができると信じています。
ここで直面しているのと同じ課題について話しているディスカッションを見ることができます: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]
コメントを追加