我开始学习 react.js,并且在 React 应用程序中开发了一个简单的剪刀石头布游戏。我发现创建一个重新加载按钮有点困难,因为它当然不同于具有以下功能的 javascript 按钮:
<button onclick="reload">RESTART GAME</button>
function reload() {
location.reload();
}
对于这个 React 应用程序,我认为可行的是:
<button type="button" onClick={ refreshPage }> <span>Reload</span> </button>
function refreshPage(){
window.location.reload();
}
到 App.js 文件,但我收到错误消息:
./src/App.js
Syntax error: Unexpected token (64:11)
62 | }
63 |
> 64 | function refreshPage(){
| ^
65 | window.location.reload();
66 | }
67 | }
完整的项目可以在这里找到github (npm start 将在终端/控制台中启动项目)
任何有关如何纠正此问题的见解将不胜感激,谢谢!
最佳答案
在 React 中,您无需刷新页面即可重置状态。我查看了您的项目,发现您将分数和游戏数据保存在组件状态中。这有助于您只需将状态设置为初始值即可轻松重置游戏。
例如
// add a method to your component for resetting state
restartGame(event) {
this.setState({ games: [] });
}
// and in your components render or any other place add the reset button
<button type="button" onClick={ this.restartGame.bind(this) }>
<span>Reload</span>
</button>
不要忘记绑定(bind)您的方法,以便能够在其中使用 this
。有关更多信息,您可以阅读 Handling Events 的 React 文档.
关于javascript - 如何在 react 应用程序中重新加载页面(状态),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46617980/