Javascript 反应-使用按钮设置状态并将其作为道具传递

Javascript 反应-使用按钮设置状态并将其作为道具传递,javascript,reactjs,meteor,Javascript,Reactjs,Meteor,我想使用“比较”按钮将比较状态切换为true或false。 接下来,我想将这个比较状态作为道具传递给pivot 在查看Toggle类时,我实际上使用了与react文档中相同的代码。 我唯一更改的是要比较的名称isToggleOn 当查看控制台客户端时,每次组件呈现时,我都会遇到以下错误: modules.js?hash=5BD2644489058B9A37CB27E36F529F99E13F95B78:3941警告:设置状态(…):无法在现有状态转换期间更新(例如在呈现或其他组件的构造函数中)。

我想使用“比较”按钮将比较状态切换为true或false。 接下来,我想将这个比较状态作为道具传递给pivot

在查看Toggle类时,我实际上使用了与react文档中相同的代码。 我唯一更改的是要比较的名称isToggleOn

当查看控制台客户端时,每次组件呈现时,我都会遇到以下错误:

modules.js?hash=5BD2644489058B9A37CB27E36F529F99E13F95B78:3941警告:设置状态(…):无法在现有状态转换期间更新(例如在
呈现
或其他组件的构造函数中)。渲染方法应该是道具和状态的纯函数;构造函数的副作用是一种反模式,但可以移动到
componentWillMount
`

我的代码如下:

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));
类仪表板扩展组件{
建造师(道具){
超级(道具);
this.state={compare:true};
this.handleClick=this.handleClick.bind(this);
}
把手舔(按钮){
如果(按钮=='比较'){
this.setState(prevState=>({
比较:!prevState.compare,
}));
}
}
render(){
返回(
这是仪表板页面。

使用此文档可以快速启动任何新项目。
{''} 你所能得到的只是这个文本和一个基本上是赤裸裸的HTML文档。

{this.state.compare?'AGGREGATE':'compare'} ); } } 导出默认值(DashboardContainer=createContainer(()=>{ //使用此方法执行所有反应式数据访问。 //请注意,卸载组件时,此订阅将被清除 const handle=Meteor.subscribe('weekly-dashboard'); 返回{ isReady:handle.ready(), gapData:WeeklyDashboard.find({}).fetch(), }; }仪表板);

有关于如何解决这个问题的建议吗

原因是这条线

这将在执行
render
函数时调用
handleClick
函数。您可以通过以下方式进行修复:

this.handleClick('compare')}>

consthandlebtnclick=()=>this.handleClick('compare');
...

工作正常,我假设您的解决方案只在单击按钮时执行函数,而不是每次渲染时执行。谢谢我需要等一分钟。