繁体   English   中英

反应-将this.state作为prop传递

[英]React - passing this.state as prop

我已经尽我所能尝试研究了,但是我仍然坚持为什么我的代码行不通。

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

我试图通过this.state作为“数据”属性中的一个属性,但是当我尝试此操作时,出现以下错误:

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

我已经搜索了错误并找到了该文档( 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'));

render方法更改为如下所示。 您需要将在getData获取的data而不是整个状态对象发送到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>

  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM