更改状态后如何只渲染一个组件?

时间:2016-12-29 19:45:17

标签: javascript reactjs

如何只显示一个<CardDetails />组件,其父组件已被点击?当我运行我的代码时,在更改状态后,我的所有CardDetails组件都会呈现。有没有其他方法,而不是为每个组件添加唯一的onclick事件和状态?

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

1 个答案:

答案 0 :(得分:0)

在CardDetails组件中添加shouldComponentUpdate方法。还将状态值作为道具发送给它。然后做一些像

这样的事情
shouldComponentUpdate(nextProps, nextState) {
  return (nextprops.cardDetails != this.props.cardDetails);
}

基本上,只要状态发生变化,这就会阻止重新呈现CardDetails组件。