преобразовать функцию реагирования в класс реакции - PullRequest
0 голосов
/ 17 октября 2019

Я пытаюсь преобразовать функцию реагирования в класс реакции

  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);
    },); 

1 Ответ

1 голос
/ 17 октября 2019

Попробуйте определить свойство useState в this.state в классе и функцию useEffect в componentDidMount.

Ваш код будет выглядеть следующим образом:

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;
...