Can not find any info about situation like this, when passing p1 props from App component to state of Child1 component, the problem: by calling buttonHandler method to see state of s1 I have got an error –> Child1.js:27 Uncaught TypeError: Cannot read properties of undefined (reading ‘state’) Why it is happening?
Class component "Child1"
import React from "react";
import { setState } from 'react'
class Child1 extends React.Component {
constructor(props) {
super(props)
this.s2 = 0
this.state = {
s1: this.props.p1
}
console.log(this.state.s1);
}
componentDidMount() {
// console.log('componentDidMount()')
console.log('s2 = ' + this.s2);
this.s2 += 1
this.setState(() => ({
s1: this.props.p1 + 1
}))
}
buttonHandler() {
console.log(this.state.s1);
}
render() {
return (
<>
<div>
<h3>State s1</h3>
<h4>{this.state.s1}</h4>
</div>
<hr />
<div>
<h3>props from p1 to s2</h3>
<h4>{this.s2}</h4>
</div>
<hr />
<div>
<button onClick={this.buttonHandler}>Push</button>
</div>
</>
)
}
}
export default Child1
App.js
import './App.css';
import Child1 from './Child1';
function App() {
return (
<>
<Child1 p1={88} />
</>
)
}
export default App;
>Solution :
With class instances, you need to bind the function to the component instance:
// Use arrow syntax (recommended) or bind in the constructor
buttonHandler = () => {
console.log(this.state.s1);
};