反应 - 传递this.state作为道具

时间:2018-01-09 22:32:53

标签: javascript reactjs

我已经尝试过无处不在的研究,但我一直坚持为什么我的代码无法运作。

我尝试使用新数据更新this.state,然后将其传递给react-bootstrap-table工具(http://allenfang.github.io/react-bootstrap-table/example

我试图通过this.state作为"数据"中的道具。 prop,但是当我尝试这个时,我得到以下错误:

react-bootstrap-table.min.js:18 Uncaught TypeError: n.props.data.slice is not a function

我已经用Google搜索了错误并找到了这个文档(https://github.com/AllenFang/react-bootstrap-table/issues/605),其中谈到了使用componentWillReceiveProps,但我对此没有运气。

任何帮助都会受到大力赞赏。

史蒂夫

class App extends React.Component {

constructor(props){
super(props);
this.state = {

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

//method to fetch data from url  
getData(url){

fetch(url)
  .then(function(resp){
    return resp.json();
  })
  .then(data => {
    //do something with the data

  this.setState(data)

  }) 
} //end of getData function

componentDidMount(){
//Details location of our data
var url = "https://fcctop100.herokuapp.com/api/fccusers/top/recent";

//fetches data from url

this.getData(url);   
} //end of componentDidMount


render(){

return (
<BootstrapTable data={this.state} striped hover>
  <TableHeaderColumn isKey dataField='username'>Username</TableHeaderColumn>
  <TableHeaderColumn dataField='recent'>Recent Score</TableHeaderColumn>
  <TableHeaderColumn dataField='alltime'>All Time Score</TableHeaderColumn>
</BootstrapTable>

);
}


} //end of App class
ReactDOM.render(<App data = {this.state}/>,
            document.getElementById('app'));

1 个答案:

答案 0 :(得分:4)

将您的render方法更改为以下内容。您需要将data中提取的getData而不是整个州对象发送到BootstrapTable。此外,您在.then中获得的数据应与BootstrapTable对数据的期望相匹配。

另请注意,组件首次渲染时不会填充this.state.data。只有在fetchUrl完成this.state.data后才会填充。

render(){

  return (
    <BootstrapTable data={this.state.data || []} striped hover>
      <TableHeaderColumn isKey dataField='username'>Username</TableHeaderColumn>
      <TableHeaderColumn dataField='recent'>Recent Score</TableHeaderColumn>
      <TableHeaderColumn dataField='alltime'>All Time Score</TableHeaderColumn>
    </BootstrapTable>

  );
}
相关问题