我应该如何为localStorage实现保存状态?

时间:2017-04-18 19:00:27

标签: javascript reactjs

CODE:

var React = require('react');
var Recipe = require('./Recipe.jsx');
var AddRecipe = require('./AddRecipe.jsx');
var EditRecipe = require('./EditRecipe.jsx');

var RecipeBox = React.createClass({


    getInitialState: function () {
        return {
           recipesArray: [],
           adding: false,
           editing: false,
           currentIndex: 0
        };
    },

    handleClick: function () {
        this.setState({
            adding: true
        }); 
    },
    handleEditClick: function(index) {
        this.setState({
            editing: true,
            currentIndex: index
        }); 
    },
    handleDeleteClick: function(index) {
        var newRecipesArray = this.state.recipesArray;
        newRecipesArray.splice(index-1,1);
        this.setState({
            recipesArray: newRecipesArray
        });
    },
    handleClose: function() {
        this.setState({
            adding: false,
            editing: false
        });
    },
    handleAdd: function(newRecipe) {
        this.setState({
            recipesArray: this.state.recipesArray.concat(newRecipe)
        });
    },
    handleEdit: function(newRecipe, index) {
        var newRecipesArray = this.state.recipesArray;
        newRecipesArray[index-1] = newRecipe;
        this.setState({
            recipesArray: newRecipesArray
        });

    },

    render: function() {
        var i = 0;
        var that = this;

        var recipes = this.state.recipesArray.map(function(item) {
            i++
            return (
                <div key={"div"+i} className="table">
                    <Recipe key={i} name={item.name} ingredients={item.ingredients} />
                    <button key ={"edit"+i} onClick={() => { that.handleEditClick(i)}} className="btn edit btn-primary">Edit</button>
                    <button  key ={"delete"+i} onClick={() => { that.handleDeleteClick(i)}} className="btn delete btn-danger">Delete</button>
                </div>
            );
        });

        return (
            <div>
                <h1>React.js Recipe Box</h1>
                <button className="btn btn-primary" onClick={this.handleClick}>Add Recipe</button>
                <table>
                    <tbody>
                        <tr>
                            <th>RECIPES</th>
                        </tr>
                    </tbody>
                </table>
                {recipes}
                { this.state.adding ? <AddRecipe handleClose={this.handleClose}  handleAdd={this.handleAdd} /> : null }
                { this.state.editing ? <EditRecipe currentIndex = {this.state.currentIndex} handleClose={this.handleClose}  handleEdit={this.handleEdit}/> : null }
            </div>
        );
    },
});

module.exports = RecipeBox;

问题:

我应该如何为localStorage实现保存状态? 什么是最优雅的实现?

目前正在学习React并希望编写干净优雅的代码。

2 个答案:

答案 0 :(得分:1)

每当触发对状态的更新时,它将触发componentDidUpdate的生命周期方法。您可以挂钩该方法以保存组件的状态。

componentDidUpdate() {
  window.localStorage.setItem('state', JSON.stringify(this.state));
}

根据您的使用情况,您应该可以在componentDidMount上重新加载。

componentDidMount() {
  // there is a chance the item does not exist
  // or the json fails to parse
  try {
    const state = window.localStorage.getItem('state');
    this.setState({ ...JSON.parse(state) });
  } catch (e) {}
}

我会警告你,你可能想要一个更像redux with a localStorage adapter的解决方案,对于一个完全成熟的&#34;解。这个方法在几个方面很脆弱。

答案 1 :(得分:0)

我会看一下使localstorage更容易(而不是特定于浏览器)的插件。一个例子就是:

https://github.com/artberri/jquery-html5storage

上面的页面包含了入门所需的所有信息。如果那个不起作用,那么我会继续搜索。那里有很多。可能有更新的也使用React。当我学习/做Angular时,jQuery插件对我有用。