Reputation: 3
I'm trying to convert react function to react class
const prevSplash = () => {
if (index === 1) {
setIndex(0);
} else {
setIndex(prev => prev - 1);
}
}
const [index, setIndex] = React.useState(0);
React.useEffect(() => {
const timer = setInterval(() => {
if (index === 1) {
setIndex(0);
} else {
setIndex(prev => prev + 1);
}
}, 10000);
return () => clearInterval(timer);
},);
Upvotes: 0
Views: 111
Reputation: 131
Try to defined useState property in this.state in class and your useEffect function in componentDidMount.
Your code will be like:
import React,{Component} from 'react';
class Demo extends Component{
constructor(props){
super(props);
this.state = {
index:0
}
}
prevSplash = () => {
if (this.state.index === 1) {
this.setState({...this.state,index:0});
} else {
this.setState((prev)=>({
index:prev.index-1
}));
}
}
componentDidMount(){
const timer = setInterval(() => {
if (this.state.index === 1) {
this.setState({...this.state,index:0});
} else {
this.setState((prev)=>({
index:prev.index+1
}));
}
}, 10000);
return () => clearInterval(timer);
};
render() {
return (
<h1>
//your code
</h1>
)
}
}
}
export default Demo;
Upvotes: 1