如何在react应用程序中重新加载页面(状态) [英] How to reload a page (state) in a react app

查看:3042
本文介绍了如何在react应用程序中重新加载页面(状态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习react.js,我在一个反应​​应用程序中开发了一个简单的石头剪刀游戏。我发现创建重新加载按钮有点困难,因为它当然与javascript按钮的功能类似:

I'm beginning to learn react.js and I've developer a simple rock paper scissors game in a react app. I'm finding it a bit difficult creating a reload button because it is of course different from the javascript button with a function like:

<button onclick="reload">RESTART GAME</button>
function reload() {
  location.reload();
}

对于这个反应应用程序,我认为可行的是:

For this react app what I thought would work was:

<button type="button" onClick={ refreshPage }> <span>Reload</span> </button>
function refreshPage(){ 
  window.location.reload(); 
}

到App.js文件但是我收到错误消息:

to the App.js file but I'm getting the error message:

./src/App.js
Syntax error: Unexpected token (64:11)

  62 |   }
  63 | 
> 64 |   function refreshPage(){
     |            ^
  65 |     window.location.reload();
  66 |   }
  67 | } 

完整的项目可以在这里找到 github (npm start将在终端/控制台启动项目)

The complete project can be found here github (npm start will launch the project in terminal/console)

任何见解如何纠正这一点将不胜感激,谢谢!

Any insight into how to correct this would be much appreciated, thank you!

推荐答案

在做出反应时你不必刷新页面来重置状态。我查看了你的项目,发现你在组件的状态下持有你的得分和游戏数据。这可以帮助您轻松重置游戏,只需将状态设置为初始值。

In react you don't have to refresh page to reset state. I looked at your project and saw that you are holding your scores and game data in component's state. This helps you to reset game easily with just setting the state to the initial values.

例如

// 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>

不要忘记绑定你的方法以便能够使用 this 在其中。有关详细信息,您可以阅读处理事件的反应文档。

Don't forget to bind your methods to be able to use this in them. For more information about that you can read react documentation for Handling Events.

这篇关于如何在react应用程序中重新加载页面(状态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆