Ad
Why Is 'this.setState' Not Working?
I'm fetching JSON data from an API endpoint and want to use this data to show a table.
Here's what I'm currently trying:
var DeliveryOptionsTHeadTh = React.createClass({
render: function() {
return (
<th>{this.props.label}</th>
);
}
});
var DeliveryOptionsTHead = React.createClass({
getInitialState : function(){
return {
data : []
}
},
componentDidMount: function() {
$.get(this.props.source, function(result) {
console.log(result);
this.setState({data: result});
}.bind(this));
},
render: function() {
return (
<thead>
<tr>
<DeliveryOptionsTHeadTh label={this.state.data.days[0].label}/>
</tr>
</thead>
);
}
});
var DeliveryOptionsTable = React.createClass({
render: function() {
return (
<table className='pure-table pure-table-horizontal'>
<DeliveryOptionsTHead source="<REDACTED>" />
<tbody>
</tbody>
</table>
);
}
});
ReactDOM.render(
<DeliveryOptionsTable />,
document.getElementById('example')
)
But this returns Uncaught TypeError: Cannot read property '0' of undefined
. Why is is this not working?
Ad
Answer
You need change initial state., as days
are Array
of Objects
and you are trying in render
method get first element from Array
but in initial state there is no days
property, that's why you are getting error
var DeliveryOptionsTHead = React.createClass({
getInitialState : function(){
return {
data: { days: [] }
}
},
componentDidMount: function() {
$.get(this.props.source, function(result) {
this.setState({data: result});
}.bind(this));
},
render: function() {
var days = this.state.data.days.map(function (day) {
return <DeliveryOptionsTHeadTh label={day.label} key={ day.date } />;
});
return <thead>
<tr>{ days }</tr>
</thead>;
}
});
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad