0

我有一个调用特定状态的函数,但有一条半相同的行。这是我的功能;

DoThis(type) {
   if (type === 'a') {
      this.setState({ activeA: { display: 'block', opacity: 1 } }, () => setTimeout(() => {
         this.setState({ activeA: { opacity: 0 } }, () => setTimeout(() => {
            this.setState({ activeA: { display: 'none' } })
         }, 300))
      }, 2000));
   } else if (type === 'b') {
      this.setState({ activeB: { display: 'block', opacity: 1 } }, () => setTimeout(() => {
         this.setState({ activeB: { opacity: 0 } }, () => setTimeout(() => {
            this.setState({ activeB: { display: 'none' } })
         }, 300))
      }, 2000));
   } // ...some other active(n) conditions.
}

它非常混乱,我只是希望它没有拥堵。

这是我的状态:

this.state ={
   activeA: { display: 'none', opacity: 0 },
   activeB: { display: 'none', opacity: 0 },
   // ...some other active(n) states...
}

有什么办法可以解决这类问题?

4

2 回答 2

1

为了逃避回调地狱,你可以添加一个简单的函数,如下所示:

const delay = (time = 0) => new Promise(r => setTimeout(r, time));

然后以线性方式重写:

async DoThis(type) {
    let key = 'active' + type.toUpperCase();

    this.setState({[key]: {display: 'block', opacity: 1}})
    await delay(300);
    this.setState({[key]: {opacity: 0}});
    await delay(2000);
    this.setState({[key]: {display: 'none'}});
}
于 2019-11-12T09:41:21.633 回答
0

使用模板字符串计算属性名称的组合:

DoThis(type) {
  const fieldName = `active${type.toUpperCase()}`;
  this.setState({[fieldName]: { display: 'block', opacity: 1 } }, () => setTimeout(() => {
     this.setState({ [fieldName]: { opacity: 0 } }, () => setTimeout(() => {
        this.setState({ fieldName]: { display: 'none' } })
     }, 300))
  }, 2000));
}

模板字符串可让您轻松构造具有复杂 JavaScript 值的字符串:

  const myString = "some text";
  const myTemplateString = `you can insert ${myString} into a template string`;
  // myTemplateString = "you can insert some text into a template string"

计算的属性值允许您在不提前知道(即“硬编码”)字段是什么的情况下将值分配给对象的字段:

  const myFieldName = "pizza";
  const myObject = {
    [myFieldName]: "delicious"
  };
  // myObject = {pizza: "delicious"}
于 2019-11-12T09:09:24.353 回答