Есть ли способ упростить длинный список кода внутри государства в React.js - PullRequest
0 голосов
/ 15 февраля 2019

У меня есть ползунок изображения {Карусель}, который имеет свои собственные тексты, и тексты скользят слева и справа.Я достиг этого, добавив каждый эффект в состоянии, используя оператор if внутри интервала, но код действительно длинный, и должен быть способ сделать это с меньшим количеством кода.спасибо заранее.

Состояние

  class Showcase extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

ComponentDidMount

  defaultState() {
    const arr = [
      "One",
      "Two",
      "Three",
      "Four",
      "Five",
      "Six",
      "Seven",
      "Eight",
      "Nine"
    ];
    const dir = ["Right", "Left"];
    const obj = { width: 0 };
    for (let i = 0; i < dir.length; i++) {
      for (let k = 0; k < arr.length; k++) {
        obj[`animate${dir[i]}${arr[k]}`] = "";
      }
    }
    return obj;
  }
  componentDidMount() {
    console.log(this.state);
    console.log(this.defaultState());
    this.sliderwidth();
    this.showAnime();
    const wow = new WOW();
    wow.init();
  }

Метод

  showAnime = () => {
    const arr = [
      "One",
      "Two",
      "Three",
      "Four",
      "Five",
      "Six",
      "Seven",
      "Eight",
      "Nine"
    ];
    let counter = 0;
    setInterval(() => {
      counter++;
      if (counter === 9) {
        this.setState(this.defaultState());
      } else {
        const state = this.state;
        state[
          `animateLeft${arr[counter]}`
        ] = `animated fadeInLeftBig delay-${arr[counter].toLowerCase()}`;
        state[
          `animateRight${arr[counter]}`
        ] = `animated fadeInRightBig delay-${arr[counter].toLowerCase()}`;
        this.setState(state);
      }
    }, 7000);
    console.log(this.state);
  };

  sliderwidth = () => {
    setInterval(() => {
      const slide = this.state.width + 100;
      this.state.width === 800
        ? this.setState({
            width: 0
          })
        : this.setState({
            width: slide
          });
    }, 7000);
  };

1 Ответ

0 голосов
/ 15 февраля 2019

Хорошо, вот код.Простая идея - создать массив чисел типа ['One','Two'...].

Способ создания состояния по умолчанию

function defaultState(){
    	  const arr = ['One','Two','Three','Four','Five','Six','Seven','Eight','Nine'];
    	  const dir = ['Right','Left']
    	  const obj = {width:0}
    	  for(let i = 0;i<dir.length;i++){
    		  for(let k = 0;k<arr.length;k++){  
    			obj[`animate${dir[i]}${arr[k]}`] = '';
    		  }
    	  }
    	  return obj;
      }
console.log(defaultState())

Функция showAmine

showAnime = () => {
    const arr = ['One','Two','Three','Four','Five','Six','Seven','Eight','Nine'];
    let counter = 0;
    setInterval(() => {
      counter++;
      if(counter === 9){
          this.setState(defaultState());
      }
      else{
          const state = this.state;
          state[`animateLeft${arr[counter]}`] = `animated fadeInLeftBig delay-${arr[counter].toLowerCase()}`
          state[`animateRight${arr[counter]}`] = `animated fadeInRightBig delay-${arr[counter].toLowerCase()}`
          this.setState(state)
      }
    }, 7000);
  };
...