Ad
Setting A State In ReactJS Gives Me: Cannot Read Property 'setState' Of Undefined
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad