So I need to run this line of code:
var vehicles = this.state.vehicles;
In the render function:
render: function(){...}
I currently get this error:
Uncaught (in promise) TypeError: Cannot read property 'state' of undefined
Even though this line works:
this.setState({vehicles: json})
This is also part of the code:
getInitialState: function(){
this.render = this.render.bind(this)
return {
vehicles: []
}
}
How can I fix this error and access the data?
You don't bind the render function. I assume that you are creating a component using React.createClass
since you are using getInitialState
to initialise the state. With React.createClass
, React automatically does the binding for you.
Even if you create a component by extending React.Component
, render method and the lifecycle functions are automatically bound to the React Component context.
Your getInitialState
function will simply be
getInitialState: function(){
return {
vehicles: []
}
}
A sample working snippet
var App = React.createClass({
getInitialState: function() {
console.log(this);
return {count: 0}
},
render: function() {
return <div>Count:{this.state.count}</div>
}
})
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With