Ad

Setting A State In ReactJS Gives Me: Cannot Read Property 'setState' Of Undefined

- 1 answer

Can not setState property it is somehow undefined

Doing a this.spin = this.spin.bind(this) in constructor gives me a Cannot read property 'bind' of undefined and doing an arrow function for spin gives me Failed to compile

import React  from 'react';
function getSeed() {
    return Math.floor(Math.random() / 2)
}
var seed = getSeed();
function spin(timer) {
    var number = timer + [i] * 0.5;
    this.setState({number: number});
}
class App extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        number:"",
      }
    };
      return (
      <div id="root"></div>
    );
}
export default App;

Ad

Answer

try like this

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      number: null,
    }
    this.getSeed = this.getSeed.bind(this);
    this.spin = this.spin.bind(this);
  };

  getSeed () {
    return Math.floor(Math.random() / 2)
  }

  spin (timer, i) {
    var number = timer + [i] * 0.5;
    this.setState({
      number: number
    });
  }

  render() {
    var v_seed = this.getSeed();
    return (
      <div>
        <button onClick = { (e) => this.spin(12, 12)} > Click here </button>
        <div>{`${v_seed} ${this.state.number}`}</div>
      </div>
    );
  }
}

ReactDOM.render( < App / > , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>

Ad
source: stackoverflow.com
Ad