簡體   English   中英

如何使用上下文API將應用程序遷移到react-redux v6和v7

[英]How to migrate app to react-redux v6 and v7 with context API

從版本6開始,使用React 16.3,react-redux添加了對Context API的支持。

// You can pass the context as an option to connect
export default connect(
  mapState,
  mapDispatch,
  null,
  { context: MyContext }
)(MyComponent)

// or, call connect as normal to start
const ConnectedComponent = connect(
  mapState,
  mapDispatch
)(MyComponent)

// Later, pass the custom context as a prop to the connected component
;<ConnectedComponent context={MyContext} />

我正在遷移我的應用程序,但是有太多地方需要添加MyContext ,我們是否有一些方法可以僅在一個地方為每個ConnectedComponent安全地添加它?

僅在必須使用多個嵌套存儲的情況下才需要connect上下文顯式傳遞給Redux Provider並進行connect如此答案中所述 這是connect不推薦使用的store選項的替代品。

如果需要使用相同的自定義上下文連接多個組件,則可以創建助手HOC:

const myConnect = (mapStateToProps = null, mapDispatchToProps = null, mergeProps = null, options = {}) => (
  connect(mapStateToProps, mapDispatchToProps, mergeProps, {...options, context: MyContext })
);

如果只有商店或它們不相交,則可以省略自定義上下文,而是使用默認的Redux上下文

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM