在項目中使用 Context API 我以前會在異步操作創建者中使用 Redux? (Using Context API in a project I would have previously used Redux in - async action creators?)


問題描述

在項目中使用 Context API 我以前會在異步操作創建者中使用 Redux? (Using Context API in a project I would have previously used Redux in ‑ async action creators?)

所以我的大多數項目都很簡單,以至於 Redux 完全是矯枉過正(儘管它一直都很好用)——我將在一個新項目上使用 Context API(它很容易完成這項工作,而且更容易向其他開發人員解釋並讓他們繼續工作)‑ Redux 有 Thunk 來處理異步操作。我認為我對事情的理解已經足夠好,以至於異步操作不會成為 Context API 的問題——Redux Thunk 實際上並沒有向 Redux 添加異步功能——它只是讓語法更容易接受。所以我的推理是,只要我編寫代碼來正確處理它們,Context API 就能夠處理任何異步操作。這是對的嗎,或者如果我想有效地處理異步操作,我是否需要堅持使用帶有 Thunk 的 Redux?


參考解法

方法 1:

I had similar question myself and came across this article that talks about a major difference between Redux and the Context API:

From https://www.academind.com/learn/react/redux‑vs‑context‑api/

The Context API (currently) is not built for high‑frequency updates (quote of Sebastian Markbage, React Team), it’s not optimized for that. The react‑redux people ran into this problem when they tried to switch to React Context internally in their package.

My personal summary is that new context is ready to be used for low frequency unlikely updates (like locale/theme). It’s also good to use it in the same way as old context was used. I.e. for static values and then propagate updates through subscriptions. It’s not ready to be used as a replacement for all Flux‑like state propagation. ‑‑‑ Sebastian Markbage

So for the moment, it seems like you might want to look into using React Context for low‑frequency updates (e.g. theme changes, user authentication) but not use it for the general state management of your application.

Hope this helps.

(by BruceMyoges nsamy)

參考文件

  1. Using Context API in a project I would have previously used Redux in ‑ async action creators? (CC BY‑SA 2.5/3.0/4.0)

#react-context #react-redux #redux-thunk #reactjs






相關問題

在項目中使用 Context API 我以前會在異步操作創建者中使用 Redux? (Using Context API in a project I would have previously used Redux in - async action creators?)

Nextjs 和上下文 API (Nextjs and Context API)

從 redux-saga 函數訪問 React 上下文值 (Access React context value from redux-saga function)

如何在 Django 應用程序中用 react ContextAPI 替換 Redux (How can you replace Redux by the react ContextAPI in a Django App)

從深度嵌套的組件更新狀態而不重新渲染父組件 (Update state from deeply nested component without re-rendering parents)

更新 useContext 中的值時,組件不會重新呈現 (Component not re rendering when value from useContext is updated)

為什麼我無法從反應上下文訪問變量?你能找出錯誤嗎? (Why am I not able to access variable from react context? Can you identify the mistake?)

React Hook useEffect 缺少依賴項(在上下文中定義的函數) (React Hook useEffect has a missing dependency (function defined in context))

React Context 是道具鑽探的解毒劑嗎? (Is React Context an antidote for prop drilling?)

主題提供者問題 (Theme Provider issue)

打字稿反應上下文+類型'{}'沒有調用簽名 (Typescript react context + Type '{}' has no call signatures)

next.js socket.io 使用效果不更新套接字消息 (next.js socket.io useeffect not updating on socket message)







留言討論