2016-12-15 101 views
0

我最近開始使用ReactJs,並試圖動態填充表格。我的代碼如下:setState(...)在未掛載組件上調用

export default class StatsTable extends React.Component { 
    constructor(){ 
     super(); 
     this.state={ 
      tableData : [], 
     } 
    } 

populateTable(){ 
    var tableDataList = []; 
    data = this.state.tableData; 
    data.map(function (row){ 
     tableDataList.push(
      <tr key={row.id}> 
      <td>{row.id}</td> 
     </tr>) 
    }); 
    return tableDataList; 
} 

handleActions(action){ 
    switch(action.type){ 
     case "TABLE_DATA_RECEIVED" : 
      var tableInput = action.data.data; 
      this.setState({tableData : tableInput}); 
      break; 
    } 
} 

loadStatsTable() { 
    loadTable(); //Triggers an ajax query that emits the message and data received 
} 

render(){ 
    return(<div> 
      <Button onClick={this.loadStatsTable.bind(this)}>Load</Button> 
      <Table> 
       <thead>{this.populateTable()}</tbody> 
      </Table> 
      </div>); 
    } 
} 

然而,我得到一個警告消息:Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the StatsTable component.

當我火了請求。 爲什麼我會收到錯誤?因爲,組件已經掛載(頁面已完全加載),當我點擊按鈕? 什麼是修復?

注意:當我嘗試使用靜態列表填充它時,populateTable()函數可以正常工作。當我使用this.setState({tableData : tableInput});

+0

什麼'loadTable'呢?以及'handleActions'如何被調用? – dfsq

+0

loadTable啓動一個AJAX調用動作,它發出「TABLE_DATA_RECEIVED」。 handleActions已經註冊到StatsTable的調度員 –

回答

2

無論你在哪裏註冊handleActions回調,您需要撤消它componentWillUnmount生命週期掛鉤。

componentWillUnmount() { 
     //Unregister handleActions from dispatcher 
} 
0

嘗試將this.state.tableData從您的渲染中傳遞到填充表中。

<Table> <thead>{this.populateTable(this.state.tableData)}</tbody> </Table>

+0

不,不工作 –

+0

嘗試進一步''this.state.tableData.map((item)=> this.buildRow(item)}''' – Christopher

相關問題