简体   繁体   中英

How to render only one component after changing its state?

How can I display only one <CardDetails /> component, whose parent was clicked? When I run my code, after changing the state all my CardDetails components render. Is there another way instead of adding unique onclick event and state for every component?

class Deck extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        cardDetails: false
      };
      // This binding is necessary to make `this` work in the callback
      this.handleClick = this.handleClick.bind(this);
      this.onClick = this.onClick.bind(this);
    }
    onClick() {
      this.setState({
        cardDetails: true,
        // when cardDetails is set as true, all <CardDetails /> components are rendered
      }, function() {
        console.log('cardDetails: ' + this.state.cardDetails + '. This.onclick: ' + this.onClick)
      });
    }
    render() {
        return ( < div className = "deck-container" > < div className = "chosen-cards" > 
        <CardHistory onClick = {
              this.onClick
            } > {
              this.state.cardDetails ? < CardDetails / > : null
            } < /CardHistory> 
            < CardHistory onClick = {this.onClick} > {
              this.state.cardDetails ? < CardDetails / > : null
            } < /CardHistory> </div > < /div> );}}
            ReactDOM.render( < Deck > < /Deck>,document.getElementById('root'));

Add a shouldComponentUpdate method in CardDetails component. Also send the state value as props to it. then do something like

shouldComponentUpdate(nextProps, nextState) {
  return (nextprops.cardDetails != this.props.cardDetails);
}

Basically this will prevent re rendering of the CardDetails component whenever the state is changed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM