javascript - 我应该如何实现将状态保存到 localStorage?

标签 javascript reactjs

代码:

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,并希望编写干净、优雅的代码。

最佳答案

每当触发状态更新时,都会触发 componentDidUpdate 的生命周期方法。您可以 Hook 该方法以保存组件的状态。

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 的解决方案寻求“成熟”的解决方案。这个在几个方面都非常脆弱。

关于javascript - 我应该如何实现将状态保存到 localStorage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43480207/

相关文章:

javascript - 使用 CSS 滚动行为时如何从 URL 中删除 #id

javascript - React Redux 中间件的 #store.dispatch(action) 与 #next(action)

node.js - 无法通过npm安装redux?

javascript - react Bootstrap 组件开关不工作

reactjs - 在 map 函数中 react setState

javascript - 如何将 id 发送到 refs(forwardrefs) 到子组件

javascript - 如何在 react 中用左右箭头滑动多个图像?

javascript - 如何抑制错误 : Illegal space before opening round brace at from jsrc?

javascript - 函数内函数内的函数似乎丢失了javascript中的临时变量

javascript - 如何使用业务 api 获取所有谷歌评论