简体   繁体   中英

React - set state using button and pass it as props

I want to use the 'compare' button to toggle the compare state to true or false. Next I want to pass this compare state to pivot as props.

I am literally using the same code as in the react documentation when looking at the Toggle class. https://facebook.github.io/react/docs/handling-events.html The only thing I changed is the name isToggleOn to compare.

When looking at the console client side I get following error every time the component renders:

modules.js?hash=5bd264489058b9a37cb27e36f529f99e13f95b78:3941 Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount .`

My code is following:

class Dashboard extends Component {
  constructor(props) {
    super(props);
    this.state = { compare: true };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(button) {
    if (button === 'compare') {
      this.setState(prevState => ({
        compare: !prevState.compare,
      }));
    }
  }

  render() {
    return (
      <Grid>
        <div className="starter-template">
          <h1>This is the dashboard page.</h1>
          <p className="lead">
            Use this document as a way to quickly start any new project.<br />{' '}
            All you get is this text and a mostly barebones HTML document.
          </p>
        </div>

        <ButtonToolbar>
          <button onClick={this.handleClick('compare')}>
            {this.state.compare ? 'AGGREGATE' : 'COMPARE'}
          </button>
        </ButtonToolbar>

        <PivotTable
          ready={this.props.isReady}
          data={this.props.gapData}
          compare={this.state.compare}
        />
      </Grid>
    );
  }
}

export default (DashboardContainer = createContainer(() => {
  // Do all your reactive data access in this method.
  // Note that this subscription will get cleaned up when your component is unmounted
  const handle = Meteor.subscribe('weekly-dashboard');

  return {
    isReady: handle.ready(),
    gapData: WeeklyDashboard.find({}).fetch(),
  };
}, Dashboard));

Any advice on how to fix this?

The reason is this line

<button onClick={this.handleClick('compare')}>

This will call the handleClick function while executing render function. You can fix by:

<button onClick={() => this.handleClick('compare')}>

Or

 const handleBtnClick = () => this.handleClick('compare'); ... <button onClick={this.handleBtnClick}> ... 

I prefer the latter

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