2017-08-11 21 views
0

我想使用'比較'按鈕將比較狀態切換爲真或假。 接下來我想通過這個比較狀態來支撐作爲道具。React - 使用按鈕設置狀態並將其作爲道具傳遞

我在字面上使用與查看Toggle類時反應文檔中相同的代碼。 https://facebook.github.io/react/docs/handling-events.html 我改變了唯一的名字是isToggleOn比較。

當我得到的所有組件呈現時間以下錯誤控制檯客戶端看:

modules.js哈希= 5bd264489058b9a37cb27e36f529f99e13f95b78:3941警告:的setState(...):不能將現有期間更新狀態轉換(例如render或另一個組件的構造函數)。渲染方法應該是道具和狀態的純粹功能;構造函數的副作用是一個反模式,但是可以移動到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)); 

就如何解決這一問題有何建議?

回答

1

原因是該行

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

在執行render功能這將調用​​功能。您可以修復由:

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

或者

const handleBtnClick =() => this.handleClick('compare'); 
 

 
... 
 
<button onClick={this.handleBtnClick}> 
 
...

我更喜歡後者

+0

完美的作品,我想點擊該按鈕時,您的解決方案只執行功能而不是每次渲染都執行。謝謝! – Christoph

+0

您能否將其標記爲答案? –

+0

Np我需要等一會兒。 – Christoph

相關問題