![](/img/trans.png)
[英]How to persist jsonwebtoken on page reload after deploying react app
[英]How to reload a page (state) in a react app
我开始学习 react.js 并且我在 React 应用程序中开发了一个简单的石头剪刀布游戏。 我发现创建重新加载按钮有点困难,因为它当然与具有以下功能的 javascript 按钮不同:
<button onclick="reload">RESTART GAME</button>
function reload() {
location.reload();
}
对于这个反应应用程序,我认为可行的是:
<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 将在终端/控制台中启动项目)
任何有关如何更正此问题的见解将不胜感激,谢谢!
在反应中,您不必刷新页面即可重置状态。 我查看了您的项目,发现您将分数和游戏数据保存在组件状态。 这可以帮助您轻松重置游戏,只需将状态设置为初始值即可。
例如
// 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
。 有关更多信息,您可以阅读处理事件的反应文档。
检查下面的代码片段以了解刷新页面的解决方法,以重置游戏。
但这不是最佳实践,因为 React 支持更改状态,这使得(默认情况下)组件重新渲染。 React 有一个叫做 Virtual DOM 的概念。 这样应用程序就会非常快。 因为 React 会通过比较 diff 来更新实际的 DOM。
最好按照其他答案的建议更改状态。 this.setState({games:[]})
以下是解决方法的代码片段(刷新页面)
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>
我喜欢文章中保留先前状态和重置功能的解决方案 - https://medium.com/@justintulk/best-practices-for-resetting-an-es6-react-components-state-81c0c86df98d
在构造函数中:
// preserve the initial state in a new object
this.baseState = this.state
和
resetForm = () => {
this.setState(this.baseState)
}
有2种方法
第二个有它的原因,但也有点贵。
方式 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>
方式2:参考@dwij答案
您真正想要的是重置状态,而不是重新加载页面。
通过在点击处理程序中调用this.setState({ games: [] })
从错误消息来看,这是一个语法错误,很可能是拼写错误或类似的东西
作为上述的一个小变化,我在我的构造函数和一个 resetPage 函数中都使用了一个 defaultState 对象。 这样默认状态只需要定义和维护一次。
例如
默认状态:
const defaultState = {
oppNum: '',
detailKey: '',
loaded: false,
showUserInput: false,
showYesNo: false,
showSubmission: false,
accepted: false,
disableSubmit: true,
showSave: true,
showModal: false,
modalOptions: {},
};
内部构造函数:
this.state = defaultState;
复位功能:
resetPage() {
this.setState(state => ({ ...defaultState }));
};
希望这会有所帮助:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.