![](/img/trans.png)
[英]How do I access the component local state in the mapDispatchToProps
[英]How do I get access to the global state in mapDispatchToProps in redux?
我想調度一個操作來更新我的應用程序的全局狀態與當前登錄的用戶。 當用戶單擊按鈕時,將觸發在mapDispatchToProps
注冊的事件處理程序,然后我想調度一個操作( article.updateAuthor(currentUser)
)。 但是,在mapDispatchToProps
我無權訪問獲取當前用戶的狀態,並且我不想將當前登錄的用戶任意傳遞給組件道具——只傳遞給上面的點擊事件,然后傳遞用戶數據到一個分派的動作。
我知道我可以使用 redux thunk 發送一個動作,這讓我可以訪問狀態。 但是,由於沒有進行 API 調用,這似乎相當笨拙。
有沒有人遇到過這個問題?
在react-redux
提供的connect
函數中,您可以使用四個可選參數:
mapStateToProps
mapDispatchToProps
mergeProps
(這個會給你你想要的)options
從mergeProps
的文檔中:
如果指定,則傳遞 mapStateToProps()、mapDispatchToProps() 和父道具的結果。 您從中返回的普通對象將作為道具傳遞給包裝的組件。 您可以指定此函數以根據 props 選擇狀態的一部分,或將動作創建者綁定到 props 中的特定變量
因此,在您的情況下,您將使用mapStateToProps
來訪問您需要的全局狀態的任何部分。 結果將作為stateProps
參數傳遞給mergeProps
。
在mergeProps
做你需要對這個狀態做的事情,使用dispatchProps
的結果(或從它解構dispatch
)並在你想要連接的組件中返回你需要的對象。
您可以考慮導入您的商店並使用store.getState()
,這樣您就可以訪問您的“全球”商店。
但請記住,不建議使用這種方法,如果您使用的是connect
mergeProps
按照@markerikson 回答的建議使用mergeProps
。
獲取狀態()
返回應用程序的當前狀態樹。 它等於 store 的 reducer 返回的最后一個值。 來源。
偽代碼:
import store from 'store'
store.getState().yourReducer.user.current
你不能。 mapDispatch
故意不授予對狀態的訪問權限,因為您通常使用mapDispatch
創建綁定函數,並且基於狀態這樣做會在狀態更改時不斷導致這些函數被重新創建。
如果你真的想這樣做,你可以使用第三個參數connect
,稱為mergeProps
,但這通常只能用作最后的手段。
推薦的方法是:
mapState
提取相關數據,並讓組件調用this.props.someFunction(this.props.someRelatedValue)
總的來說,在 thunk 中訪問狀態是一種完全有效且受支持的功能。 有些人擔心這樣做是否是一個好主意,我在我的博客文章Idiomatic Redux: Thoughts on Thunks, Sagas, Abstraction, and Reusability 中解決了這些問題。
在 mapDispatchToProps 中無法訪問狀態是荒謬的。
redux 有一個替代方案, Dynadux ,它很簡單,解決了 Redux 的繁瑣。
此外,可以在沒有 Thunk 的情況下從減速器中觸發 ispatches。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.