在Action Creators 中存取Redux 狀態
問題:
問題:在Redux 應用程式中,如何可以從動作創建者內部存取全域儲存狀態嗎?以下方法是否合適?
<code class="javascript">import store from '../store'; export const SOME_ACTION = 'SOME_ACTION'; export function someAction() { return { type: SOME_ACTION, items: store.getState().otherReducer.items, } }</code>
方法1:
<code class="javascript">export const SOME_ACTION = 'SOME_ACTION'; export function someAction() { return (dispatch, getState) => { const {items} = getState().otherReducer; dispatch(anotherAction(items)); } }</code>
方法2:
在Action Creator 中存取狀態的可接受性是Redux 社群內爭論的話題。
方法 1:
不鼓勵直接透過 store.getState() 存取狀態,因為它依賴 store 是全域單例。在伺服器上,每個請求可能存在單獨的存儲,這種方法是有問題的。
方法 2:
這種方法是首選,因為它使用 Redux Thunk 中間件,允許非同步操作並透過 getState() 檢索儲存狀態。 Thunk 在用戶端和伺服器上無縫運作,並確保狀態存取與特定操作隔離。
鼓勵在thunk 中使用getState,因為它利用了專門為此類用例設計的功能.
最終,這兩種方法都可以產生預期的結果,但方法2 是建議的最佳實踐,可以避免潛在的陷阱並保持跨環境的一致性。以上是Redux Action 創建者應該如何存取狀態:從 Store 還是 Thunk?的詳細內容。更多資訊請關注PHP中文網其他相關文章!