Constructor
new Game(props)
- Set up the initial state of the game: board configuration, number of moves and if "X" is the next to play.
- Set the Board’s initial state to contain an array of 9 nulls corresponding to the 9 squares.
Conceptually, components are like JavaScript functions:
- They accept arbitrary inputs (called “props”) and
- return React elements describing what should appear on the screen.
Parameters:
Name | Type | Description |
---|---|---|
props |
Object | component input. |
Extends
- React.Component.<Props>
Members
state :Object
Type:
- Object
Properties:
Name | Type | Description |
---|---|---|
state.history |
Array.<Object.<{squares: Array.<String>}>> | history array. |
state.stepNumber |
Number | step number. |
state.xIsNext |
Boolean | player turn. |
state.setState |
state_setter | setter - change state. |
- Source:
Methods
handleClick(i)
The Square calls this.handleClick(i) when clicked.
Each time a player moves, xIsNext (a boolean) will be flipped to determine which player goes next, and the game’s state will be saved.
If you “go back in time” and then make a new move from that point, you only want to keep the history up to that point. Instead of adding nextSquares after all items in history, you’ll add it after all items in history.slice(0, stepNumber + 1), so that you’re only keeping that portion of the old history.
Note how in handleClick, we call slice() to create a copy of the squares array, instead of modifying the existing array.
To explain why, we need to discuss immutability, and why immutability is important to learn.
There are generally two approaches to changing data:
- The first approach is to mutate the data, by directly changing the data’s values.
- The second approach is to replace the data with a new copy, which has the desired changes.
- if the immutable object that is being referenced is different than the previous one, then the object has changed.
Parameters:
Name | Type | Description |
---|---|---|
i |
Number | an index ∈ [0..8] corresponding to the button clicked. |
- Source:
- See:
jumpTo(step)
Go to the step-th move in the game.
Enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state.
This is the primary method you use to update the user interface in response to event handlers and server responses.Parameters:
Name | Type | Description |
---|---|---|
step |
Number | position into the history array. |
render() → {HTMLDivElement}
Returns:
- Type
- HTMLDivElement