Reputation: 4562
I am trying to generate an html table based on a Rest web service call using React. Only table header was displayed. The table rows are blank. If I debug it, after line
tableModel.rows = this.state.rows;
tableModel.rows was 'undefined'.
I counldn't figure out what's the issue.
<!DOCTYPE html>
<html>
<head>
<title>React Flux</title>
<script src="https://fb.me/react-0.13.3.js"></script>
<script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="container" style="color:red"></div>
<script type="text/jsx">
var tableModel = {
cols: ["id", "name"],
rows: [],
}
var Table = React.createClass({
getInitialState: function () {
return {text: ''};
},
componentDidMount: function(){
$.ajax({
url: "http://localhost:8080/rest/user/findAll"
}).then(function(data) {
this.setState({
rows: data});
}.bind(this))
},
render: function() {
tableModel.rows = this.state.rows;
var _self = this;
var thead = React.DOM.thead({},
React.DOM.tr({},
this.props.cols.map(function (col) {
return React.DOM.th({}, col);
})));
var tbody = this.props.rows.map(function (row) {
return React.DOM.tr({},
_self.props.cols.map(function (col) {
return React.DOM.td({}, row[col] || "");
}));
});
return React.DOM.table({}, [thead, tbody]);
}
});
React.render(<Table cols={tableModel.cols} rows={tableModel.rows} />, container);
</script>
</body>
</html>
Upvotes: 2
Views: 505
Reputation: 510
When your Table
setState
, it's render
function will be recall, but why do you think it's props would be repopulate? It stay the same, mean Table this.props.rows === []
. You could fix it by put the tableModel
into Table state
and using this.state
instead of this.props
, or wrap another class to Table
to manage data fetching and populate data to Table
class.
Upvotes: 1