首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何避免重复实例化对象

如何避免重复实例化对象
EN

Stack Overflow用户
提问于 2019-05-01 15:11:03
回答 2查看 96关注 0票数 1

我使用的是reactjs,在componentDidUpdate()中有一个实例化。但当更新状态时,componentDidUpdate()将被执行,对象将重复语句

代码语言:javascript
复制
ps: const barrage = new Barrage();  the object will be execute repeatly

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


const barrage = new Barrage(); 

如何避免Object语句重复执行

EN

回答 2

Stack Overflow用户

发布于 2019-05-01 15:22:41

您还没有真正解释您想要实现什么,但我将尝试通过以下方式来解决此特定问题:如果您只需要创建一次新实例,则可以将其置于一种状态

代码语言:javascript
复制
constructor(props) {
  super(props);   
  ...
  this.state = {
     barrage : null
   }
  ...
}

 componentDidUpdate(prevState) {
  if(!prevState.barrage) {
    this.setState({ barrage : new Barrage() )}
  }
}
票数 1
EN

Stack Overflow用户

发布于 2019-05-01 15:36:31

您可以在componentDidMount中创建它,然后在componentWillUnmount中进行清理

代码语言:javascript
复制
class TestComponent extends React.Component {
  barage = null;

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

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

在没有任何代码的情况下,很难猜测你对这个对象做了什么。我只能假设它独立于组件的更新(如果有)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55932758

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档