2016-12-15 23 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

相关问题