简体   繁体   English

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

[英]Using recompose branch within a React container component

I have a container component for a modal. 我有一个模态的容器组件。 It imports LabelDetailForm, which is adds the modal's content to the page using React portals. 它导入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 can prevent the modal's contents from appearing in the DOM by checking the value of props.showModal in it's render method. LabelDetailForm可以通过检查其render方法中props.showModal的值来防止模式内容出现在DOM中。 However, according to the React Developer Tools extension for Chrome, the LabelDetailForm component always exists. 但是,根据针对Chrome的React Developer Tools扩展,LabelDetailForm组件始终存在。 To save memory, I want the container component to only export LabelDetailForm when showModal is true. 为了节省内存,我希望容器组件仅在showModal为true时才导出LabelDetailForm。

I tried to use branch(): 我尝试使用branch():

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

However, the LabelDetailForm never appears even when showModal is true and I get the following warning in the console: 但是,即使showModal为true,LabelDetailForm也永远不会出现,并且我在控制台中收到以下警告:

Warning: Functions are not valid as a React child.

The second and third arguments of branch() are higher-order components, instead of components or null . branch()的第二个和第三个参数是高阶组件,而不是component或null You can use renderComponent() and renderNothing() to create the HOCs: 您可以使用renderComponent()renderNothing()创建renderNothing()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM