【问题标题】:Using recompose branch within a React container component在 React 容器组件中使用 recompose 分支
【发布时间】:2019-01-25 01:00:31
【问题描述】:

我有一个用于模态的容器组件。它导入 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 可以通过检查其 render 方法中 props.showModal 的值来防止 modal 的内容出现在 DOM 中。但是,根据 Chrome 的 React Developer Tools 扩展,LabelDetailForm 组件始终存在。为了节省内存,我希望容器组件只在 showModal 为 true 时导出 LabelDetailForm。

我尝试使用分支():

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

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

Warning: Functions are not valid as a React child.

【问题讨论】:

    标签: javascript reactjs recompose


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-21
      • 2018-03-13
      • 2018-09-27
      • 1970-01-01
      • 2017-12-31
      • 2018-11-30
      • 2018-10-28
      • 2017-08-09
      • 2017-07-06
      相关资源
      最近更新 更多