首页 > 解决方案 > 有没有办法简化 React.js 中状态内的一长串代码

问题描述

我有一个图像滑块{Carousel},它有自己的文本,文本从左右滑入。我通过在间隔内使用 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);
  };

标签: javascriptreactjsif-statementstatesetinterval

解决方案


好的,这里是代码。简单的想法是创建一个数字数组,例如['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())

显示胺功能

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

推荐阅读