2017-10-07 34 views
0

我開始學習react.js和我已經開發了一個簡單的岩石紙剪刀遊戲在一個反應​​的應用程序。我發現它有點困難,創造重載按鈕,因爲它當然是有相似的功能從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開始發現將啓動終端項目/ C鞋墊)

任何洞察到如何糾正這將不勝感激,謝謝!

+0

是內部分量代碼? –

回答

3

在反應中,您不必刷新頁面以重置狀態。我看着你的項目,看到你將分數和遊戲數據保持在組件狀態。只需將狀態設置爲初始值,這可以幫助您輕鬆重置遊戲。

對於實例

// 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。有關更多信息,請閱讀Handling Events的反應文檔。

+0

這是完美的!非常感謝bennygenel! –

0

查看下面的代碼片段以找到更新頁面的解決方法,以便重置遊戲。

但是,這並不是最好的做法,因爲React支持更改使(默認情況下)組件重新呈現的狀態。 React具有稱爲虛擬DOM的概念。所以這個應用會非常快。因爲React會通過比較差異來更新實際的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>

0

你真正想要的是重置狀態,而不是重新加載頁面。

通過單擊處理程序

從錯誤信息來看調用this.setState({ games: [] })這是一個語法錯誤,最有可能的一個錯字或類似的

0

的東西有兩種方法來

  • 任你可以通過重置狀態
  • 重置遊戲中你可以重新加載網頁並重置反應中的應用。

第二個有其道理,但有點昂貴的爲好。

方式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答案

相關問題