代码之家  ›  专栏  ›  技术社区  ›  Optiq

React:使用spread运算符更新State内的数组返回的结果比需要的多1000倍

  •  0
  • Optiq  · 技术社区  · 6 年前

    我正在尝试从 .map() 方法在 render() 方法。当前,我要映射的数组中有9个对象,我希望从中提取属性并将其添加到状态内的数组中。什么时候? console.log()

    下面是我正在迭代的九个对象之一的示例

    {
      "name": "Trap_808",
      "key" : "Q",
      "path": "https://firebasestorage.googleapis.com/v0/b/online-coding.appspot.com/o/drum%20samples%2Ftrap-808-08.wav?alt=media&token=c3c63635-45b0-4c99-82ff-e397f1153fa0"
    }
    

    下面是如何在构造函数中定义状态的。

    this.state = { currentSound: '', triggerKeys: [] };
    

    我要做的是添加 key 属性从对象到 triggerKeys 对象被迭代时的属性。这就是我用 .map() 方法。

    <ul id="pad-shell">
      {
        DRUM_PATCH.map( sound =>{
          this.setState({ triggerKeys: [...this.state.triggerKeys, sound.key] });
    
          console.log(this.state);
    
          return <DrumButton
                   name={sound.name}
                   soundKey={sound.key}
                   sourceLink={sound.path}
                   trigger={this.updateSound}
                 />
         });
       }
    </ul>
    

    我也试着像这样更新状态

    this.setState( prevState =>{ return { triggerKeys: [...prevState.triggerKeys, sound.key] } });
    

    2 回复  |  直到 6 年前
        1
  •  1
  •   Tyler Sebastian    6 年前

    正如其他人所说,你不应该使用 this.setState 内部 render -这样做很可能会导致无限的更新循环。

    您没有提供足够的代码上下文来给出明确的答案,但是

    DRUM_PATCH 来自道具

    class Component extends React.Component {
      constructor (props) {
        super(props)
    
        this.state = { triggerKeys: props.drumPatch.map(s => s.key) }
      }
    
    
      render() {
        ...
      }
    }
    

    如果 鼓形补片 只是一个常数

    this.state = { triggerKeys: props.drumPatch.map(s => s.key) }
    

    变成

    this.state = { triggerKeys: DRUM_PATCH.map(s => s.key) }
    
        2
  •  1
  •   Atul    6 年前

    this.setState({ triggerKeys: [...this.state.triggerKeys, sound.key] });
    

    这就是罪魁祸首