Javascript 如何在反应应用程序中重新加载页面(状态)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46617980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reload a page (state) in a react app
提问by T.Doe
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:
我开始学习 react.js 并且我在 React 应用程序中开发了一个简单的石头剪刀布游戏。我发现创建重新加载按钮有点困难,因为它当然与具有以下功能的 javascript 按钮不同:
<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();
}
to the App.js file but I'm getting the error message:
到 App.js 文件,但我收到错误消息:
./src/App.js
Syntax error: Unexpected token (64:11)
62 | }
63 |
> 64 | function refreshPage(){
| ^
65 | window.location.reload();
66 | }
67 | }
The complete project can be found here github(npm start will launch the project in terminal/console)
完整的项目可以在这里找到github(npm start 将在终端/控制台中启动项目)
Any insight into how to correct this would be much appreciated, thank you!
任何有关如何更正此问题的见解将不胜感激,谢谢!
回答by bennygenel
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.
在反应中,您不必刷新页面即可重置状态。我查看了您的项目,发现您将分数和游戏数据保存在组件状态。这可以帮助您轻松重置游戏,只需将状态设置为初始值即可。
For Example
例如
// 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>
Don't forget to bind your methods to be able to use thisin them. For more information about that you can read react documentation for Handling Events.
不要忘记绑定您的方法以便能够this在它们中使用。有关更多信息,您可以阅读处理事件的反应文档。
回答by dwij
Check the code snippet below for workaround for the refreshing page in order to reset the game.
检查下面的代码片段以了解刷新页面的解决方法,以重置游戏。
But this is not the best practice since React support changing the state which makes (by default) the component re-render. React has the concept called Virtual DOM. so that the app will be pretty fast. Because React will update the actual DOM by comparing diff.
但这不是最佳实践,因为 React 支持更改状态,这使得(默认情况下)组件重新渲染。React 有一个叫做 Virtual DOM 的概念。这样应用程序就会非常快。因为 React 会通过比较 diff 来更新实际的 DOM。
It is best to change the state as other answers suggested. this.setState({games:[]})
最好按照其他答案的建议更改状态。 this.setState({games:[]})
Below is the code snippet for workaround(refreshing page)
以下是解决方法的代码片段(刷新页面)
class App extends React.Component {
render() {
return ( < button onClick = {this._refreshPage} > test </button>);
}
_refreshPage() {
console.log("Clicked");
window.location.reload();
}
}
ReactDOM.render( < App / > , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
回答by Akash Bhandwalkar
There are 2 ways to
有2种方法
- either you can reset the Game by resetting state
- You can reload the web page and reset the react application.
- 您可以通过重置状态来重置游戏
- 您可以重新加载网页并重置反应应用程序。
Second one has its reason but bit costly as well.
第二个有它的原因,但也有点贵。
way 1 - Refering to @bennygel answer
方式 1 - 参考@bennygel 答案
// 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>
way 2 : Refering to @dwij answer
方式2:参考@dwij答案
回答by Aleksandr Golovatyi
I like solution in the article with keeping previous state and reset function - https://medium.com/@justintulk/best-practices-for-resetting-an-es6-react-components-state-81c0c86df98d
我喜欢文章中保留先前状态和重置功能的解决方案 - https://medium.com/@justintulk/best-practices-for-resetting-an-es6-react-components-state-81c0c86df98d
In Constructor:
在构造函数中:
// preserve the initial state in a new object
this.baseState = this.state
and
和
resetForm = () => {
this.setState(this.baseState)
}
回答by Olly Brand
As a minor variation on the above, I use a defaultState object in both my constructor and a resetPage function. This way the default state only needs to be defined and maintained once.
作为上述的一个小变化,我在我的构造函数和一个 resetPage 函数中都使用了一个 defaultState 对象。这样默认状态只需要定义和维护一次。
e.g.
例如
defaultState:
默认状态:
const defaultState = {
oppNum: '',
detailKey: '',
loaded: false,
showUserInput: false,
showYesNo: false,
showSubmission: false,
accepted: false,
disableSubmit: true,
showSave: true,
showModal: false,
modalOptions: {},
};
Inside Constructor:
内部构造函数:
this.state = defaultState;
Reset Function:
复位功能:
resetPage() {
this.setState(state => ({ ...defaultState }));
};
Hope this helps :D
希望这有帮助:D
回答by Krisztian Balla
What you really want is to reset the state, not reloading the page.
您真正想要的是重置状态,而不是重新加载页面。
By calling this.setState({ games: [] })in the click handler
通过调用this.setState({ games: [] })点击处理程序
Judging from the error message it's a syntax error, most likely a typo or something like that
从错误消息来看,这是一个语法错误,很可能是拼写错误或类似的东西

