如何将反应状态存储到本地存储中?

时间:2018-09-16 13:17:30

标签: javascript json reactjs local-storage jsx

我开始学习React并创建了一个Todo应用程序,我想将任务状态存储到本地存储中。我怎样才能做到这一点?这是我的代码:

Tasks.js

import React, { Component } from 'react';
import AddTask from './AddTask';
import Task from './Task';

class Tasks extends Component {
    state = {
        tasks:[
          {
            task:'Learn web development'
          },
          {
            task:'Learn mobile app development'
          }
        ]
      }

      componentDidMount() {
        localStorage.tasks = JSON.stringify(this.state.tasks);
      }

      addTask = (newTask) => {
        let tasks = [...this.state.tasks, newTask];
        this.setState({
            tasks:tasks
        });
      }

      render() {
        return (
          <div className="tasks">
            <AddTask addTask={this.addTask}/>
            <Task tasks={this.state.tasks}/>
          </div>
     );
  }
}

export default Tasks;

AddTask.js

import React, { Component } from 'react';

class AddTask extends Component {
    state = {
        task:''
    }

    handleChange = (e) => {
         this.setState({task:e.target.value});
    }

    handleSubmit = (e) => {
        e.preventDefault();

        if(this.state.task!=='') {
            this.props.addTask(this.state);
        }

        this.setState({
            task:''
        });
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input type="text" id="task" placeholder="What should I do?" className="textbox" autoComplete="off" onChange={this.handleChange} value={this.state.task} autoFocus/>
            </form>
        );
    }
}

export default AddTask;

Task.js

import React from 'react';

const Task = ({tasks}) => {
    let task = tasks.map(task => {
        return (
            <li key={task.task}><input type="checkbox"/>{task.task}</li>
        )
    })

    return (
        <ul>
            {task}
        </ul>
    )
}
export default Task;

这是可行的,但是即使重新加载页面后,我也想在添加新状态后保持状态。因此,我希望它存储在本地存储中。数据库是一种解决方案,但我只希望将其存储在本地而不使用DB。有可能吗?

1 个答案:

答案 0 :(得分:0)

添加新任务时,可以像这样在localStorage中设置

localStorage.setItem("tasks", JSON.stringify(tasks) + ',');

,在Tasks.js组件的状态下,您将获得任务并将其用逗号分割,从而获得一个数组。

state = {
   tasks: localStorage.getItem('tasks').split(',')
{