Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access state from render function

Tags:

reactjs

state

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?

like image 886
Ed Lynch Avatar asked Jan 04 '23 16:01

Ed Lynch


1 Answers

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>
like image 53
Shubham Khatri Avatar answered Jan 28 '23 17:01

Shubham Khatri