我正在尝试将撤销和重做的更改历史记录写入正在制作的React级别编辑器中,但是我遇到了问题。
由于某种原因,当我尝试存储级别数组的当前状态时,在任何setState之前,它将存储更改后的级别数组。 我认为这是值变量的问题,它存储的是值(this.state.value)的地址而不是它的值(如指针),因为当我向历史记录中添加更多状态时,所有级别数组都是一样。
我不知道发生了什么事,所以我来这里寻求帮助。我在做什么错了?
// App.js
class App extends React.Component {
EMPTY = 0;
PLAYER = 1;
constructor(props) {
super(props);
this.state = {
'changeHistory': [],
'undoHistory': [],
'activeTool': 2, //This number is used to change level index numbers
'width': 1,
'height': 1,
'value': {
level: [ // Level array
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,]
],
},
'errors': []
};
}
// Save the history
getValue = () => {
let value = this.state.value;
const level = value.level.slice();
let changeHistory = this.state.changeHistory;
if (changeHistory.length > 7)
changeHistory.splice(0, 1);
changeHistory.push(level);
console.log("");
console.log("Saving history");
console.log("Level", level); // Should log the level array as it is
console.log("History:", changeHistory); // before any changes
console.log("");
return value;
}
tileClick = (x, y) => {
console.log("");
console.log("Tile click");
const { activeTool } = this.state;
let value = this.getValue(); // Call the function that saves the history
console.log("Got value");
console.log("Level", value.level.slice()); // Should log the level unchanged, but
// logs a changed level instead
// ...
value.level[y][x] = activeTool;
this.setState({ value: value, errors: this.getErrors(value) }) // This is the first time
this.change(value, value.errors); // That level is changed
console.log("");
};
render() {
return (
// There is a lot of things here, but I simplified
<div style={{ width: '320px', height: '32px' }} onClick={() => { this.tileClick(0, 0); }} }>
{ 'Click here to change the level'}
</div >
)
}
}