【问题标题】:Why the push function repeat the objects in a array in React为什么 push 函数在 React 中重复数组中的对象
【发布时间】:2022-01-21 03:46:28
【问题描述】:

我正在尝试构建一个引擎来控制 React 中一些自定义矩形的物理特性。为了实现这一点,我创建了两个类,一个扩展“React.component”的 Body 类和一个具有名为“objectsInWorld”的数组以保持跟踪的 Engine 类。 当我实例化一个身体时,问题就来了。该主体接收引擎的实例并调用引擎的方法“addBody”以将该主体包含在“objectsInWorld”中,但它复制了它们。 我附上主要代码:

export default class Body extends React.Component {

constructor(props){
    super(props);
    ...

    // add this body to the world controlled by the engine
    this.engine = props.engine;
    this.engine.addBody(this);

和引擎一:

export class Engine {
    constructor(props) {
        ...

        this.objectsInWorld = [];

        this.addBody = (body) => {
            console.log(this.objectsInWorld);
            this.objectsInWorld.push(body);
            console.log(this.objectsInWorld);
        }
    }

一格一地后的结果:

[Square] 
[Square, Square] 
[Square, Square, Ground]
[Square, Square, Ground, Ground]

我会很感激任何帮助(如果很明显很抱歉):)

【问题讨论】:

    标签: arrays reactjs duplicates


    【解决方案1】:

    尽管我不明白为什么它不起作用,但我找到了一个解决方案。解决方案是将调用“this.engine.addBody(this)”移动到componentDidMount() {}部分而不是在构造函数中,

    // start up the component
    componentDidMount() {
    
         // add this body to the world controlled by the engine
         this.engine.addBody(this);
         console.log(this.engine.objectsInWorld);
    
    }
    

    希望它可以帮助别人。

    【讨论】:

      猜你喜欢
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 2019-02-22
      • 2018-07-05
      • 2023-01-22
      • 2021-11-11
      • 2018-10-06
      • 1970-01-01
      相关资源
      最近更新 更多