I try to learn React and I have an issue. I want to make an example myself from the tutorial.
import React, { Component } from 'react';
class MyComponent extends Component {
state = {
persons: [],
firstPersons: 5,
variables: {
Id: '1',
first: this.firstPersons,
input: {},
}
}
render() {
console.log('this.state', this.state);
return (
<div>
<p>Hello React!!!</p>
</div>
);
}
}
export default MyComponent;
I put in render method a console.log(this.state).
I have this simple state in my page, and when I run the project I get the error:
Uncaught TypeError: Cannot read property 'firstPersons' of undefined
Please someone tell me what is wrong on my code?
You can't access the object inside of itself in JS. You should do:
import React, { Component } from 'react';
var myVar = 5;
class MyComponent extends Component {
state = {
persons: [],
firstPersons: myVar,
variables: {
Id: '1',
first: myVar,
input: {},
}
}
render() {
console.log('this.state', this.state);
return (
<div>
<p>Hello React!!!</p>
</div>
);
}
}
export default MyComponent;
or
import React, { Component } from 'react';
class MyComponent extends Component {
state = {
persons: [],
firstPersons: 5,
variables: {
Id: '1',
input: {},
}
}
componentWillMount() {
this.state.variables.first = this.state.firstPersons;
this.setState(this.state);
}
render() {
console.log('this.state', this.state);
return (
<div>
<p>Hello React!!!</p>
</div>
);
}
}
export default MyComponent;
or if componentWillMount() is deprecated
import React, { Component } from 'react';
class MyComponent extends Component {
state = {
persons: [],
firstPersons: 5,
variables: {
Id: '1',
input: {},
}
}
static getDerivedStateFromProps(props, state) {
this.state.variables.first = this.state.firstPersons;
this.setState(this.state);
}
render() {
console.log('this.state', this.state);
return (
<div>
<p>Hello React!!!</p>
</div>
);
}
}
export default MyComponent;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With