我使用的是reactjs,在componentDidUpdate()中有一个实例化。但当更新状态时,componentDidUpdate()将被执行,对象将重复语句
ps: const barrage = new Barrage(); the object will be execute repeatly
componentDidUpdate() {
const barrage = new Barrage();
}
const barrage = new Barrage(); 如何避免Object语句重复执行
发布于 2019-05-01 15:22:41
您还没有真正解释您想要实现什么,但我将尝试通过以下方式来解决此特定问题:如果您只需要创建一次新实例,则可以将其置于一种状态
constructor(props) {
super(props);
...
this.state = {
barrage : null
}
...
}
componentDidUpdate(prevState) {
if(!prevState.barrage) {
this.setState({ barrage : new Barrage() )}
}
}发布于 2019-05-01 15:36:31
您可以在componentDidMount中创建它,然后在componentWillUnmount中进行清理
class TestComponent extends React.Component {
barage = null;
componentDidMount() {
this.barage = new Barage();
}
componentWillUnmount() {
this.barage = null;
}
}在没有任何代码的情况下,很难猜测你对这个对象做了什么。我只能假设它独立于组件的更新(如果有)。
https://stackoverflow.com/questions/55932758
复制相似问题