如何使用上下文API将应用程序迁移到react-redux v6和v7

时间:2019-04-22 03:29:50

标签: reactjs react-redux

从版本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添加它?

1 个答案:

答案 0 :(得分:1)

仅在必须使用多个嵌套存储的情况下才需要将上下文显式传递给Redux Providerconnect,如this answer中所述。这是store中已弃用的connect选项的替代。

如果需要使用相同的自定义上下文连接多个组件,则可以创建助手HOC:

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

如果只有商店或它们不相交,则可以省略自定义上下文,而将使用default Redux context