2017-04-06 37 views
12

我在這裏看到了與其他問題有關的衝突(或者僅僅是令人困惑),在這裏有關在動作中使用getState是否可以接受的答案,並且我已經看到很多次被稱爲反模式。對我來說,它似乎工作得很好,但如果我們不使用getState,那麼這樣做的最佳做法是什麼?在Redux Thunk good practice中使用getState?

我在thunk中使用了getState來過濾當前連接到某些模擬數據並被拉入應用程序狀態的用戶數組。

這裏是我的行動代碼:

export const accountLogInSuccess = user => ({ 
    type: types.ACCOUNT_LOG_IN_SUCCESS, 
    user, 
}); 

export const accountLogOutSuccess =() => ({ 
    type: types.ACCOUNT_LOG_OUT_SUCCESS, 
}); 

export const accountCheckSuccess =() => ({ 
    type: types.ACCOUNT_CHECK_SUCCESS, 
}); 

export const accountCheck =() => (
    (dispatch, getState) => { 
     dispatch(ajaxCallBegin()); 
     return apiAccount.accountCheck().then((account) => { 
      if (account) { 
       const user = findByUID(getState().users, account.uid); 
       dispatch(accountLogInSuccess(user)); 
       toastr.success(`Welcome ${user.nameFirst}!`); 
      } else { 
       dispatch(accountLogOutSuccess()); 
      } 
      dispatch(accountCheckSuccess()); 
     }).catch((error) => { 
      dispatch(ajaxCallError(error)); 
      toastr.error(error.message); 
      throw (error); 
     }); 
    } 
); 

我的減速器:

export default function reducerAccount(state = initial.account, action) { 
    switch (action.type) { 
    case types.ACCOUNT_LOG_IN_SUCCESS: 
     return Object.assign({}, state, action.user, { 
      authenticated: true, 
     }); 
    case types.ACCOUNT_LOG_OUT_SUCCESS: 
     return Object.assign({}, { 
      authenticated: false, 
     }); 
    case types.ACCOUNT_CHECK_SUCCESS: 
     return Object.assign({}, state, { 
      initialized: true, 
     }); 
    default: 
     return state; 
    } 
} 

在我的減速器使用賬戶的初始狀態就是:

account: { 
    initialized: false, 
    authenticated: false, 
}, 

accountCheck動作通過用戶(使用getState和找到函數)分解爲accountLogInSuccess,其中reducer通過Object.assign將其值添加到當前帳戶狀態。

不需要讓用戶在我的應用程序的根目錄下,然後通過道具傳遞它,在Redux中完成此操作並使用戶數據可用狀態的最佳實踐是什麼?同樣,在thunk中使用getState迄今爲止對我來說非常有用,但是有沒有更好的解決方案來解決這個問題,這不是一種反模式?

回答

12

我寫了一篇名爲Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability的擴展博客文章,詳細討論了這個話題。其中,我回應了幾次對thunk的批評和使用getState(包括Dan Abramov在Accessing Redux state in an action creator?中的評論)。事實上,我的文章特別受到像你們這樣的問題的啓發。

作爲我的文章的TL; DR:我認爲thunk是在Redux應用程序中使用的完全可行的工具,並鼓勵他們使用。雖然在使用thunk和傳奇時需要注意一些有效的注意事項,並在其中使用getState/select,但這些擔憂不應該讓您遠離使用thunk。

相關問題