在 React 容器组件中使用重组分支

Using recompose branch within a React container component

我有一个模态容器组件。它导入 LabelDetailForm,使用 React 门户将模式的内容添加到页面。

import {compose, branch} from 'recompose'
import {actionCreators as uiActionCreators} from '../../redux/reducers/ui/uiActions'
import {connect} from 'react-redux'
import LabelDetailForm from '../../forms/labelDetail/labelDetailForm'

export function mapStateToProps (state, props) {
    return {
        showModal: state.ui.showLabelDetailModal
    }
}

export const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        closeModal: () => {
            dispatch(uiActionCreators.toggleLabelDetailModal())
        }
    }
}

export default compose(
    connect(mapStateToProps, mapDispatchToProps)
)(LabelDetailForm)

LabelDetailForm 可以通过在它的呈现方法中检查 props.showModal 的值来防止模式的内容出现在 DOM 中。但是,根据 Chrome 的 React Developer Tools 扩展,LabelDetailForm 组件始终存在。为了节省内存,我希望容器组件仅在 showModal 为 true 时导出 LabelDetailForm。

我尝试使用 branch():

export default compose(
    connect(mapStateToProps, mapDispatchToProps),
    branch(
        ({ showModal }) => showModal,
        LabelDetailForm,
        null
    )
)

但是,即使 showModal 为真,LabelDetailForm 也不会出现,我在控制台中收到以下警告:

Warning: Functions are not valid as a React child.

branch()的第二个和第三个参数是高阶分量,而不是分量或null。您可以使用 renderComponent() and renderNothing() 创建 HOC:

branch(
  ({ showModal }) => showModal,
  renderComponent(LabelDetailForm),
  renderNothing
)