今、react tutorialの「Storing a History - 履歴を記録する」を実践中です。https://mae.chab.in/archives/2943
以下のコードでstatusから定数を設定したい(const history = this.state.history;)のですが、文法エラーが出ており、statusが定義されていないと怒られます。
おそらく定数をクラスの中に直接打ち込んでいるのが原因なのです。
ですが、constructorの中のstateを呼び出す方法がなぜ間違っているのか、そしてどうすれば解決するか教えていただきたいです。
react
1import React, { Component } from 'react'; 2/*Component省略 Square, Bord*/ 3 4class Game extends React.Component { 5 constructor() { 6 super(); 7 this.state = { 8 history: [{ 9 squares: Array(9).fill(null) 10 }], 11 xIsNext: true 12 }; 13 } 14 const history = this.state.history; 15 const current = history[history.length - 1]; 16 const winner = calculateWinner(current.squares); 17 18 let status; 19 if (winner) { 20 status = 'Winner: ' + winner; 21 } else { 22 status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O'); 23 } 24 25 handleClick(i) { 26 var history = this.state.history; 27 var current = history[history.length - 1]; 28 const squares = current.squares.slice(); 29 if (calculateWinner(squares) || squares[i]) { 30 return; 31 } 32 squares[i] = this.state.xIsNext ? 'X' : 'O'; 33 this.setState({ 34 history: history.concat([{ 35 squares: squares 36 }]), 37 xIsNext: !this.state.xIsNext, 38 }); 39 } 40 41 render() { 42 return ( 43 <div className="game"> 44 <div className="game-board"> 45 <Board 46 squares={current.squares} 47 onClick={(i) => this.handleClick(i)} 48 /> 49 </div> 50 <div className="game-info"> 51 <div>{status}</div> 52 <ol>{/* TODO */}</ol> 53 </div> 54 </div> 55 ); 56 } 57} 58 59function calculateWinner(squares) { 60 const lines = [ 61 [0, 1, 2], 62 [3, 4, 5], 63 [6, 7, 8], 64 [0, 3, 6], 65 [1, 4, 7], 66 [2, 5, 8], 67 [0, 4, 8], 68 [2, 4, 6], 69 ]; 70 for (let i = 0; i < lines.length; i++) { 71 const [a, b, c] = lines[i]; 72 if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { 73 return squares[a]; 74 } 75 } 76 return null; 77} 78 79 80 81export default Game; 82
./src/App.js Syntax error: Unexpected token (77:8) 75 | }; 76 | } > 77 | const history = this.state.history; | ^ 78 | const current = history[history.length - 1]; 79 | const winner = calculateWinner(current.squares);
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/15 13:00