完整的反应代码。
Subscriptions
我的问题是handleClick更新构造函数,然后componentDidUpdate触发,调用 class Square extends React.Component{
render(){
const letters = this.props.print;
const print = letters === 0 ? "" : letters;
return(
<div>
<button className='boxes' onClick={this.props.onClick}>
{print}
</button>
</div>
);
}
}
class Game extends React.Component{
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
letter: 'O',
gameWon: false,
letterArr: [0,0,0,0,0,0,0,0,0],
winArr: [
'X,X,X,0,0,0,0,0,0',
'0,0,0,X,X,X,0,0,0',
'0,0,0,0,0,0,X,X,X',
'X,0,0,X,0,0,X,0,0',
'0,X,0,0,X,0,0,X,0',
'0,0,X,0,0,X,0,0,X',
'X,0,0,0,X,0,0,0,X',
'0,0,X,0,X,0,X,0,0',
'O,O,O,0,0,0,0,0,0',
'0,0,0,O,O,O,0,0,0',
'0,0,0,0,0,0,O,O,O',
'O,0,0,O,0,0,O,0,0',
'0,O,0,0,O,0,0,O,0',
'0,0,O,0,0,O,0,0,O',
'O,0,0,0,O,0,0,0,O',
'0,0,O,0,O,0,O,0,0'
]
};
}
componentDidUpdate(){
let o_s = this.state.letterArr.map((o) => {return o == 'X' ? 0 : o}).toString();
let x_x = this.state.letterArr.map((x) => {return x == 'O' ? 0 : x}).toString();
let oWin = (this.state.winArr.indexOf(o_s) != -1);
let xWin = (this.state.winArr.indexOf(x_x) != -1);
if( oWin == true ){
console.log("O WINS!!!");
board(gameVar.mode, gameVar.letter);
}else if( xWin == true ){
console.log("X WINS!!!");
board(gameVar.mode, gameVar.letter);
}
}
handleClick(i){
let letter = this.state.letter;
let arr = this.state.letterArr.slice();
let change = this.state.letter == "O" ? "X" : "O";
arr[i] = letter;
this.setState({letter: change});
this.setState({letterArr: arr});
}
squares(i){
if(this.state.letterArr[i] == 0){
return(
<Square
print={this.state.letterArr[i]}
onClick={() => {this.handleClick(i)}}
/>
);
}else{
return(
<Square
print={this.state.letterArr[i]}
/>
);
}
}
render(){
return(
<div className='justify'>
{this.squares(0)}
{this.squares(1)}
{this.squares(2)}
{this.squares(3)}
{this.squares(4)}
{this.squares(5)}
{this.squares(6)}
{this.squares(7)}
{this.squares(8)}
</div>
);
}
}
ReactDOM.render(
<Game />,
document.getElementById('root')
);
}
。我期待Board()
内的setState首先重新渲染我的类handleClick
。
Box
?答案 0 :(得分:0)
您的代码存在许多问题。在render
组件的Game
方法中,您调用方法Box()
,但该方法不返回任何值。即使它确实你需要进行一些更改,因为我假设你想要多个框来渲染。此外,Box()
组件上的Game
方法也不会将任何值作为参数,但您使用数字调用它。
在您的Box
组件中,您从属性const num
中提取print
,但print
未从Game
组件传递到组件。
还有很多其他问题......我认为这不是完整的代码,因此没有解决所有问题。
答案 1 :(得分:0)
setState
显然componentDidUpdate
和setTimeout
是异步的。在我的组件呈现之前,我使用setState
暂停->
componentDidUpdate
@mixin Eloquent
。