从版本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
添加它?
答案 0 :(得分:1)
仅在必须使用多个嵌套存储的情况下才需要将上下文显式传递给Redux Provider
和connect
,如this answer中所述。这是store
中已弃用的connect
选项的替代。
如果需要使用相同的自定义上下文连接多个组件,则可以创建助手HOC:
const myConnect = (mapStateToProps = null, mapDispatchToProps = null, mergeProps = null, options = {}) => (
connect(mapStateToProps, mapDispatchToProps, mergeProps, {...options, context: MyContext })
);
如果只有商店或它们不相交,则可以省略自定义上下文,而将使用default Redux context。