React教程-2 版本v16.2.0

进阶

现在,每个状态都封装到了每个方格组件里。要完成整个游戏,我们要检查一个玩家是否赢得比赛,还有除了X还有O放到方格。为了检查是否赢,我们需要在一个地方获取9个方格信息,而不是每一个方格组件。

You might think that Board should just inquire what the current state of each Square is. Although it is technically possible to do this in React, it is discouraged because it tends to make code difficult to understand, more brittle, and harder to refactor.

 

Instead, the best solution here is to store this state in the Board component instead of in each Square – and the Board component can tell each Square what to display, like how we made each square display its index earlier.

When you want to aggregate data from multiple children or to have two child components communicate with each other, move the state upwards so that it lives in the parent component. The parent can then pass the state back down to the children via props, so that the child components are always in sync with each other and with the parent.

Pulling state upwards like this is common when refactoring React components, so let’s take this opportunity to try it out. Add a constructor to the Board and set its initial state to contain an array with 9 nulls, corresponding to the 9 squares:

发表评论

邮箱地址不会被公开。