[英]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可以通過檢查其render方法中props.showModal的值來防止模式內容出現在DOM中。 但是,根據針對Chrome的React Developer Tools擴展,LabelDetailForm組件始終存在。 為了節省內存,我希望容器組件僅在showModal為true時才導出LabelDetailForm。
我嘗試使用branch():
export default compose(
connect(mapStateToProps, mapDispatchToProps),
branch(
({ showModal }) => showModal,
LabelDetailForm,
null
)
)
但是,即使showModal為true,LabelDetailForm也永遠不會出現,並且我在控制台中收到以下警告:
Warning: Functions are not valid as a React child.
branch()
的第二個和第三個參數是高階組件,而不是component或null
。 您可以使用renderComponent()
和renderNothing()
創建renderNothing()
:
branch(
({ showModal }) => showModal,
renderComponent(LabelDetailForm),
renderNothing
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.