1

我正在使用 reactjs,并且在componentDidUpdate(). 但是当更新状态时,componentDidUpdate()将被执行并且对象将重复语句

ps: const barrage = new Barrage();  the object will be execute repeatly

componentDidUpdate() {
    const barrage = new Barrage();
}


const barrage = new Barrage(); 

如何避免Object语句重复执行

4

2 回答 2

1

您可以在其中创建componentDidMount并清理componentWillUnmount

class TestComponent extends React.Component {
  barage = null;

  componentDidMount() {
    this.barage = new Barage();
  }

  componentWillUnmount() {
    this.barage = null;
  }
}

没有任何代码,真的很难猜出你在用那个对象做什么。我只能假设它独立于组件的更新(如果有的话)。

于 2019-05-01T07:36:31.293 回答
1

您还没有真正解释您想要实现的目标,但我会尝试解决这个特定问题,如果您需要它来创建新实例一次,您可以将其置于一个状态

constructor(props) {
  super(props);   
  ...
  this.state = {
     barrage : null
   }
  ...
}

 componentDidUpdate(prevState) {
  if(!prevState.barrage) {
    this.setState({ barrage : new Barrage() )}
  }
}
于 2019-05-01T07:22:41.043 回答