[英]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.