I'm trying to learn me some React but can't seem to understand it.
How would I access this.state.planet in newMove()?
Uncaught TypeError: Cannot read property 'state' of undefined is what I get.
Here is app.js
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = newPlay();
}
render() {
return (
<div>
<button onClick={(e) => newMove(e)}>New Move</button>
</div>
);
}
}
and here is logic.js
export const newPlay = () => ({
planet: 'Earth',
position: [0, 0, 0, 0, 0, 0, 0, 0, 0],
active: true,
shots: 5
});
export const newMove = () => {
let player = this.state.planet === 'Earth' ? 'Human' : 'Alien';
console.log(player);
this.setState({
shots: this.state.shots++,
active: false
})
}
thisand arrow functions work. That has nothing to do with React but basic JavaScript. When you call the function withnewMove(e), how should JavaScript know thatthisshould refer to your component instance? I recommend to read developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…this, you don't want to update the components state based onthis.state. Pass a function tosetStateinstead. See reactjs.org/docs/react-component.html#setstate .