简体   繁体   中英

How to reload a page (state) in a react app

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(); 
}

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

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.

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 this in them. For more information about that you can read react documentation for Handling Events .

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.

It is best to change the state as other answers suggested. 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>

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

In Constructor:

// preserve the initial state in a new object
this.baseState = this.state 

and

resetForm = () => {
  this.setState(this.baseState)
}

There are 2 ways to

  • 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

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

What you really want is to reset the state, not reloading the page.

By calling this.setState({ games: [] }) in the click handler

Judging from the error message it's a syntax error, most likely a typo or something like that

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.

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM