我现在已经挣扎了一段时间了,好像我走在了正确的轨道上,但我绝对没有在哪里。
以下是代码:
constructor(props) {
super(props);
this.interval = null;
this.state = {
scored: null,
score: 0,
highScore: 0,
totalScore: 0,
teamScore: 0
};
}
componentWillMount() {
this.createHighScore();
}
createHighScore = async () => {
try {
const highScore = await AsyncStorage.getItem('highScore');
const score = await AsyncStorage.getItem('score');
if (score > highScore) await AsyncStorage.setItem('highScore', score);
this.setState({ highScore: Number(highScore) });
} catch (e) {
console.log(e);
}
};
这是处理分数增量
的函数内部 if (this.state.scored === null) {
if (this.state.y + radius > NET_Y + NET_HEIGHT / 2 && nextState.y + radius < NET_Y + NET_HEIGHT / 2) {
if (nextState.x + radius > NET_LEFT_BORDER_X && nextState.x + radius < NET_RIGHT_BORDER_X) {
nextState.scored = true;
nextState.score +=1;
} else {
nextState.scored = false;
}
}
}
}
基本上,我正在尝试使用AsyncStorage设置highScore,这样只要应用程序重新登录,它就会始终为用户存储。我觉得我做错了哈哈。
如果由于我还在学习JS和RN而没有充分理解,我道歉。
欣赏它们
答案 0 :(得分:0)
在获取AsyncStorage值之前,您必须在其上设置初始值,这样当您阅读它时,您可以比较值,得分和高分。
例如:
constructor(props) {
super(props);
//Set default values for score and highScore
AsyncStorage.setItem('score', 0);
AsyncStorage.setItem('highScore', 0);
this.interval = null;
this.state = {
scored: null,
score: 0,
highScore: 0,
totalScore: 0,
teamScore: 0
};
}
componentWillMount() {
this.createHighScore();
}
createHighScore = async () => {
try {
const highScore = await AsyncStorage.getItem('highScore');
const score = await AsyncStorage.getItem('score');
//Fix this. Now your highscore should be the score
if (score > highScore) {
await AsyncStorage.setItem('highScore', score);
this.setState({ highScore: Number(score) });
}
} catch (e) {
console.log(e);
}
};