Reputation: 1067
I got this error when I call this.state.testState inside a function.
TypeError: Cannot read property 'state' of undefined
class Home extends Component {
constructor(props){
super(props);
this.state = {
testState: 'hello'
}
}
render(){
function testing(){
let testState123 = this.state.testState
//some codes
return testState123;
}
return(
<div>
{testing()}
</div>
);
}
}
export default Home;
Upvotes: 2
Views: 4806
Reputation: 15688
The this
keyword is undefined inside your testing
function. This is just one of the many nuances of React. Typically, in traditional vanilla JavaScript, the this
keyword refers to the closest object that is one level higher than the context it is used in (without binding).
However, in React you use classes instead, and when defining a method, like you did, the this
keyword does not implicitly bind to your component's execution context. Instead, the this
keyword is undefined
because there is no higher object that owns this component.
There are a couple of ways to solve our problem and they all revolve around binding the this
keyword to your component.
You could explicitly bind the function in your constructor, which will point the this
keyword to your component's context.
class Home extends Component {
constructor(props){
super(props);
this.state = {
testState: 'hello'
}
this.testing = this.testing.bind(this)
}
function(testing){
let testState123 = this.state.testState
//some codes
return testState123;
}
render(){
return(
<div>
{this.testing()}
</div>
);
}
}
export default Home;
Or your can use an arrow-function, which has lexical-binding. Which essentially just means that the function you defined inherits the overarching context of its parent. In this case, it is the class component.
class Home extends Component {
constructor(props){
super(props);
this.state = {
testState: 'hello'
}
}
testing = () => {
let testState123 = this.state.testState
//some codes
return testState123;
}
render(){
return(
<div>
{this.testing()}
</div>
);
}
}
export default Home;
Worth noting, its a good rule-of-thumb to declare your methods
outside of render
as a means of separating logic from mark-up.
Upvotes: 2
Reputation: 486
Use arrow function or another to bind "this"
const testing= ()=>{
let testState123 = this.state.testState
//some codes
return testState123;
}
Upvotes: 0