【发布时间】:2018-10-10 15:04:27
【问题描述】:
我正在尝试在使用 reactJS 构建的 tic tac toe 应用程序中构建一个撤消按钮,为此我遵循了 Youtube 中的教程:
以下是我的文件:
App.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './App.css';
import Status from'./components/Status';
class App extends Component {
constructor(props){
super(props)
this.state = {
board : Array(9).fill(null),
player : null,
winner : null,
isUndoRedo: false
}
}
checkWinner(){
let winLines =
[
["0", "1", "2"],
["3", "4", "5"],
["6", "7", "8"],
["0", "3", "6"],
["1", "4", "7"],
["2", "5", "8"],
["0", "1", "3"],
["0", "4", "8"],
["2", "4", "6"]
]
this.checkmatch(winLines)
}
checkmatch(winLines){
for (let index = 0; index < winLines.length; index++) {
const [a,b,c]=winLines[index];
let board = this.state.board;
if(board[a] && board[a] === board[b] && board[a] === board[c]){
alert('You won!');
this.setState({
winner : this.state.player
})
}
}
}
handleClick(index){
if(this.state.player && !this.state.winner){
let newBoard = this.state.board
if(this.state.board[index]===null){
newBoard[index] = this.state.player
this.setState({
board: newBoard,
player: this.state.player==="X" ? "O" : "X"
})
this.checkWinner()
}
}
}
setPlayer(player){
this.setState({player})
}
renderBoxes(){
return this.state.board.map(
(box, index) =>
<div className="box" key={index}
onClick={()=> {this.handleClick(index)}}>
{box}
</div>
)
}
reset(){
this.setState({
board : Array(9).fill(null),
player : null,
winner : null
})
}
undo = (e) => { //Code for undoing the last move
e.preventDefault();
this.props.undoRedo.undo();
this.setState({
isUndoRedo: true,
});
};
render() {
return (
<div className="container">
<h1>Tic Tac Toe App</h1>
<Status
player={this.state.player}
setPlayer={(e) => this.setPlayer(e)}
winner = {this.state.winner}
/>
<div className="board">
{this.renderBoxes()}
</div>
<button className='reset' disabled ={!this.state.winner} onClick = {() => this.reset()}> Reset </button>
<button className='reset' onClick = {this.undo}> Undo </button>
</div>
);
}
}
App.propTypes = {
undoRedo: PropTypes.object.isRequired,
val: PropTypes.string.isRequired,
update: PropTypes.func.isRequired,
};
export default App;
我在添加撤消按钮时遵循了这个link,但每当我单击撤消按钮时它都会显示错误
TypeError:无法读取未定义的属性“撤消”
代码this.props.undoRedo.undo();。
我附上了截图
这是在 ReactJS 中实现 UNDO 按钮以便用户可以撤消最后一步的正确方法吗?如果没有,有人可以建议我更好的方法来实现这一目标吗?我是 ReactJS 的超级新手,我正在学习它,如果这是一个愚蠢的问题,请原谅我。
【问题讨论】:
-
你想用 this.props.undoRedo.undo(); 做什么?我看不出这行代码有什么好处
-
撤消当前更改并将其移至上一个状态。
-
您在哪个状态属性设置当前更改?
标签: javascript reactjs react-native react-redux tic-tac-toe