Using LocalStorage with React?

后端 未结 5 839
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 09:08

From what I am experiencing so far, it doesn\'t seem like ReactJS updates with the state of localStorage. My code below.

var Frr = React.createClass({
getIni         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-13 09:29

    Here is just another Example:

    import React from 'react'
    class App extends React.Component {
      constructor(props) {
        super(props);
        var storedClicks = 0;
    
        if (localStorage.getItem('clicks')) {
          storedClicks = parseInt(localStorage.getItem('clicks'));
        }
    
        this.state = {
          clicks: storedClicks,
        };
        this.click = this.click.bind(this);
      }
    
      click() {
        var newclick = this.state.clicks + 1;
        this.setState({clicks: newclick});
        // Set it
        localStorage.setItem('clicks', newclick);
      }
    
      render() {
        return (
          

    Click the button a few times and refresh page

    Counter {this.state.clicks}
    ); } } export default App;

提交回复
热议问题