Access state from render function

17,078

Solution 1

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>

Solution 2

You need to define the initial state, it looks like you didn't, therefore you are getting that error.

class YourComponent extends PureComponent {
  state = {}; // <-- Initialize the state
}

Or using the constructor

class YourComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {}; // <-- Initialize the state
  }
}

Or using ES5 (Deprecated)

var YourComponent = React.createReactClass({

  getInitialState: function() {
    return {};  // <-- Initialize the state
  },

  // ...

});

Solution 3

To use this.setState, you first have to declare the state variable on this reference inside your component.

You do that in the consturctor, like this:

constructor(props) {
  super(props);
  this.state = {...};
}

You can read more about local state in the React docs: Adding Local State to a Class.

Solution 4

It seems to be a context bind problem.

Cannot read property 'state' of undefined

That means this is undefined. I guess you're using it in some change handler. Try to onChange={this.changeHandler.bind(this)}.

Share:
17,078
Ed Lynch
Author by

Ed Lynch

So I get like a point for filling this in?

Updated on June 04, 2022

Comments

  • Ed Lynch
    Ed Lynch about 2 years

    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?