Я пытаюсь создать кнопку отмены в приложении крестики-нолики, созданном с использованием responseJS, для которого я следовал руководству в 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;
Я следил за этим ссылка при добавлении кнопки Undo, но он показывает ошибку всякий раз, когда я нажимаю кнопку Undo, заявляя, что
TypeError: Cannot read property 'undo' of undefined
для кода this.props.undoRedo.undo();.
Прикрепил скриншот
Это правильный способ реализации кнопки UNDO в ReactJS, чтобы пользователь мог ОТМЕНИТЬ последний ход? Если нет, может ли кто-нибудь предложить мне лучший способ добиться этого? Я новичок в ReactJS и изучаю его, прошу прощения, если это глупый вопрос.
Отменить текущее изменение и переместить его в предыдущее состояние.
В каком состоянии собственности вы устанавливаете текущее изменение?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Из документация я понимаю, что вам нужно сначала вызвать this.props.undoRedo.addStep в handleClick, а затем, когда вы нажмете на отмену, отмена будет работать. В вашем handleClick сделайте это
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()
}
}
setTimeout(() => {
this.props.undoRedo.addStep();
});
}
Что вы пытаетесь сделать с this.props.undoRedo.undo () ;? Я не вижу пользы от этой строчки кода