简体   繁体   English

更改状态数组后,react.js不会更新DOM

[英]react.js does not update DOM after having changed state array

I am trying to implement a game in react where I have the board as an two dimensional array in the initial state of the parent class. 我正在尝试实现一个反应游戏,在父类的初始状态下将板作为二维数组。 Tiles are rendered by iterating through that array. 通过迭代该数组来渲染图块。 I pass those children a function as a prop so that they can change that state array. 我为那些孩子传递了一个函数作为道具,以便他们可以更改该状态数组。

Now, when I use that function to change the array, the HTML does not update. 现在,当我使用该函数更改数组时,HTML不会更新。 The array gets updated when I call setState but it never rerenders. 当我调用setState时,该数组会更新,但它不会重新渲染。 I tried this.forceUpdate() but still no luck. 我尝试了this.forceUpdate()但还是没有运气。 What I then did was to pass a function from that child to the parent through the function to update that child's state and this works, but I need the function from the parent to call itself recursively to update the board. 然后,我要做的就是通过该函数将那个孩子的功能传递给父母,以更新那个孩子的状态,这是可行的,但是我需要父母的功能来递归地调用自身以更新电路板。 I feel like I might have hit an anti-pattern. 我觉得我可能打了反模式。 How could I change my code in order for the DOM to update, please? 请问如何更改代码以更新DOM?

There is parts missing but those are all the components involved. 缺少一些零件,但是所有零件都包括在内。 statusBoard is the internal version of the board featuring the solution. statusBoard是具有该解决方案的开发板的内部版本。 I hope this is clear. 我希望这很清楚。

Whenever you are linking props and state together you have to create a componentWillReceiveProps function like so: 每当将道具和状态链接在一起时,就必须创建一个componentWillReceiveProps函数,如下所示:

componentWillReceiveProps: function(nextProps) {
    this.setState({
      positionX: nextProps.columnPosition,
      positionY: nextProps.rowPosition
    });
  }

When games state changes and passes it down as props to Field, fields own internal state doesn't get updated at that point because it is relying on its own state. 当游戏状态发生变化并将其作为道具传递给Field时,字段本身的内部状态此时不会更新,因为它依赖于其自身的状态。 this is an anti pattern and you should avoid Field having to have any state and just rely on its props it gets passed and have a parent component that is handling the state of everything. 这是一种反模式,您应该避免Field必须具有任何状态,而仅依赖于它传递的道具并拥有一个处理所有状态的父组件。

https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM