有条件的渲染Redux和反应

问题描述:

我有一个ComponentonClick事件。此事件设置在我的global state一些booleantrue。怎么可以,取决于这个boolean渲染/隐藏另一个component有条件的渲染Redux和反应

我可以写类似

<ParentCompononet 

    conditionalRendering(props) { 
     if(props.boolean) { 
      <ConditionalComponent /> 
     } else { 
      null 
     } 

    render() { 
     return (
      { conditionalRendering } 
     ) 
/> 

不知道这将是正确的方式

+0

可能*太*宽,因为你目前有它:)你能够'连接'状态变量的组件'道具'? –

+0

@DavinTryon我认为是的,是的 – Stophface

一旦你connect布尔值的道具,你可能只是做这样的事情(伪!):

const MyComponent = (props) => { 

    return { props.myBool && <MyChildComponent /> }; 

} 

或稍微详细:

const MyComponent = (props) => { 

    if (props.myBool) { 
     return <MyChildComponent />; 
    } else { 
     return null; 
    }  
} 
+0

我编辑了我的问题。几乎我在伪代码中写的我认为? – Stophface

+0

是的,看起来差不多:) –

+0

太棒了。不知道这是否是正确的方式/最佳做法来做到这一点! – Stophface

假设您已配置react-redux propely,这可能是您正在寻找的那个。

import React, { Component } from 'react'; 
import PropTypes from 'prop-types'; 
import {connect} from 'react-redux'; 
import {bindActionCreators} from 'redux'; 
import * as Actions from '../../actions'; 



class User extends Component { 
    constructor(props) { 
     super(props); 

    } 

    click=()=>{ 
    this.props.actions.someEvent(); 
    } 

    render() { 

     return (
     <div> 
     (this.props.useravailable) ? <div>Hello world!</div> : <div/> 
     </div> 
    ); 
    } 
} 

Login.PropTypes = { 
    useravailable: PropTypes.bool.isRequired, 
    actions: PropTypes.object.isRequired 
} 

let mapStateToProps = (state,props) => { 
    return { 
    useravailable: state.user 
    } 
} 

let mapDispatchToProps = (dispatch) => { 
    return { 
    actions:bindActionCreators(Actions,dispatch) 
    }; 
} 

export default connect(mapStateToProps,mapDispatchToProps)(User);