条件渲染Redux和React

时间:2017-05-25 11:21:01

标签: javascript reactjs redux

我有ComponentonClick个事件。此事件在global state部分boolean设置为true。如何根据此boolean呈现/隐藏另一个component

我可以写一些像(伪代码!)

的东西
<ParentCompononet

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

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

不确定这是不是正确的方法

2 个答案:

答案 0 :(得分:2)

一旦你connect道具的布尔值,你就可以这样做:

const MyComponent = (props) => {

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

}

或稍微冗长:

const MyComponent = (props) => {

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

答案 1 :(得分:0)

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

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);