Reputation: 77
I don't understand why state returns undefined
My code is this:
class s extends React.Component {
constructor(props) {
super(props);
this.state = {
name:null,
uri:null,
fbid:null,
};
}
componentDidMount() {
setInterval(function(){..
if(this.state.fbid!=null){..
..),1000}
this.state.fbid => is undefined
Upvotes: 1
Views: 789
Reputation: 10709
this
is out of context of your function, reason because setInterval function creates their own scope. Try arrow functions instead.
componentDidMount() {
setInterval(() => {
if(self.state.fbid!=null){
// do something
};
}, 1000);
}
Upvotes: 2
Reputation: 151
defining functions will create their own scope here. and this
bounds to function scope. because state
is not in function scope you can't access it hence undefined. try using arrow functions instead:
componentDidMount() {
setInterval(() => {
//do anything
}, 1000)
}
Upvotes: 0
Reputation: 11
i guess, in react custom component names should start with capital letter.
https://codesandbox.io/s/kolwq50kj5, working as expected.
Upvotes: 0