我应该如何为localStorage实现保存状态? [英] How should I implement saving state to localStorage?

查看:56
本文介绍了我应该如何为localStorage实现保存状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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实现保存状态?
什么是最优雅的实现?

How should I implement saving state to localStorage ? What would be the most elegant implementation ?

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

Currently learning React and looking to write clean and elegant code.

推荐答案

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

Whenever an update to state is fired, it will trigger the lifecycle method of componentDidUpdate. You can hook into that method in order to save the state of the component.

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

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

Depending on your use case, you should be able to load it back up on 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 localStorage adapter 的完全成熟解决方案的解决方案。这一点在几个方面非常脆弱。

I would warn you, you probably want a solution more like redux with a localStorage adapter for a "full-fledged" solution. This one is pretty frail in a few different ways.

这篇关于我应该如何为localStorage实现保存状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆