2017-05-25 132 views
0

我有一個ComponentonClick事件。此事件設置在我的global state一些booleantrue。怎麼可以,取決於這個boolean渲染/隱藏另一個component有條件的渲染Redux和反應

我可以寫類似

<ParentCompononet 

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

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

不知道這將是正確的方式

+0

可能*太*寬,因爲你目前有它:)你能夠'連接'狀態變量的組件'道具'? –

+0

@DavinTryon我認爲是的,是的 – Stophface

回答

1

一旦你connect布爾值的道具,你可能只是做這樣的事情(僞!):

const MyComponent = (props) => { 

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

} 

或稍微詳細:

const MyComponent = (props) => { 

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

我編輯了我的問題。幾乎我在僞代碼中寫的我認爲? – Stophface

+0

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

+0

太棒了。不知道這是否是正確的方式/最佳做法來做到這一點! – Stophface

0

假設您已配置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);