[英]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.