如何将反应 js 状态保存到本地存储中 [英] how to save react js state into localstorage

查看:14
本文介绍了如何将反应 js 状态保存到本地存储中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何将 react js 状态存储到 localstorage 中.

import React, { Component } from 'react'导入'./App.css';从 './firebase/firebase.utils' 导入 { auth,createUserProfileDocument }从 './components/TodoForm/TodoForm.component' 导入 { TodoForm }从 './components/TodoList/TodoList.component' 导入 {TodoList}从 './components/footer/footer.component' 导入 {Footer}从'../src/components/header/header.component'导入标题从'react-router-dom'导入{重定向}从react-redux"导入 {connect}从 './redux/user/user.actions' 导入 {setCurrentUser}导出类 App 扩展组件 {构造函数(道具){超级(道具)this.input=React.createRef()this.state = {待办事项:[{id:0, content:'欢迎先生!',isCompleted:null},]}}todoDelete = (id) =>{const todos = this.state.todos.filter(todo => {返回 todo.id !== id})this.setState({待办事项})}toDoComplete = (id,isCompleted) =>{控制台日志(已完成)var todos = [...this.state.todos];var index = todos.findIndex(obj => obj.id === id);todos[index].isCompleted = !isCompleted;this.setState({todos});控制台日志(已完成)}addTODO = (todo) =>{todo.id = Math.random()todo.isCompleted = true让 todos = [...this.state.todos, todo]this.setState({待办事项})}unsubscribeFromAuth = null;componentDidMount() {const { setCurrentUser } = this.props;this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {如果(用户身份验证){const userRef = await createUserProfileDocument(userAuth);userRef.onSnapshot(snapShot => {设置当前用户({id: snapShot.id,...snapShot.data()});});}setCurrentUser(userAuth);});}componentWillUnmount() {this.unsubscribeFromAuth();}使成为() {返回 (

<标题/><TodoForm addTODO={this.addTODO}/><待办事项列表todos={this.state.todos}todoDelete={ this.todoDelete}toDoComplete={ this.toDoComplete}/><页脚/>

)}}const mapStateToProps = ({ user }) =>({当前用户:user.currentUser});const mapDispatchToProps = dispatch =>({setCurrentUser: 用户 =>调度(设置当前用户(用户))});导出默认连接(mapStateToProps,mapDispatchToProps)(应用程序);

在我的输入表单中

<代码>导入'./TodoForm.style.css'导出类 TodoForm 扩展组件 {构造函数(道具){超级(道具)this.state = {内容 : ''}}handleChange = (e) =>{this.setState({内容:e.target.value})}handleSubmit =(e) =>{e.preventDefault();this.props.addTODO(this.state);this.setState({内容: ''})}使成为() {返回 (

<form onSubmit={ this.handleSubmit}><输入类名=文本框"类型='文本'onChange={ this.handleChange}值={this.state.content}占位符='你想做什么...'/></表单>

)}}导出默认 TodoForm

我不知道如何将 react js 状态存储到 localstorage 中.我在互联网上搜索,但无法找到我认为必须发布的所有代码的确切解决方案.

解决方案

读出 componentDidMount 回调中的 localStorage 项.只需阅读您想要获取的项目,检查它是否存在并将其解析为需要的可用对象、数组或数据类型.然后使用从存储中获取的结果设置状态.

为了存储它,只需在事件处理程序或辅助方法中处理它以更新状态和 localStorage 项.

class ExampleComponent extends Component {构造函数(){极好的();this.state = {某物: {foo: '酒吧'}}}componentDidMount() {const storedState = localStorage.getItem('state');如果(存储状态!== 空){const parsedState = JSON.parse(storedState);this.setState({ something: parsedState });}}clickHandler = (事件) =>{常量值 = event.target.value;const stringifiedValue = JSON.stringify(value);localStorage.setItem('state', stringifiedValue);this.setState({ something: value });}使成为() {返回 (<button onClick={clickHandler} value={this.state.something}>点击我</button>);}}

I have no idea How to store the react js state into localstorage.

import React, { Component } from 'react'
import './App.css';
import { auth,createUserProfileDocument } from './firebase/firebase.utils'
import { TodoForm } from './components/TodoForm/TodoForm.component'
import {TodoList} from './components/TodoList/TodoList.component'
import {Footer} from './components/footer/footer.component'
import Header from '../src/components/header/header.component'
import {Redirect} from 'react-router-dom'

import {connect} from 'react-redux'
import {setCurrentUser} from './redux/user/user.actions'

export class App extends Component {
  constructor(props) {
    super(props)

    this.input=React.createRef()
    this.state = {
        todos:[
         {id:0, content:'Welcome Sir!',isCompleted:null},
        ]


    }
  }

  todoDelete = (id) =>{
    const todos = this.state.todos.filter(todo => {
      return todo.id !== id 
    })
    this.setState({
      todos
    })
  }
   toDoComplete = (id,isCompleted) =>{
     console.log(isCompleted)
     var todos = [...this.state.todos];
     var index = todos.findIndex(obj => obj.id === id);
     todos[index].isCompleted = !isCompleted;
     this.setState({todos});
     console.log(isCompleted)
      }

  addTODO = (todo) =>{
         todo.id = Math.random()
         todo.isCompleted = true
         let todos = [...this.state.todos, todo]
         this.setState({
           todos
         })
  }


 unsubscribeFromAuth = null;

 componentDidMount() {
  const { setCurrentUser } = this.props;

  this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
    if (userAuth) {
      const userRef = await createUserProfileDocument(userAuth);

      userRef.onSnapshot(snapShot => {
        setCurrentUser({
          id: snapShot.id,
          ...snapShot.data()
        });
      });
    }

    setCurrentUser(userAuth);
  });
}

componentWillUnmount() {
  this.unsubscribeFromAuth();
}

  render() {
    return (

      <div className='App'>
            <Header />
            <TodoForm addTODO={this.addTODO} />
            <TodoList 
              todos={this.state.todos} 
              todoDelete={ this.todoDelete} 
              toDoComplete={ this.toDoComplete}
           />
            <Footer/>
      </div>
    )
  }
}

const mapStateToProps = ({ user }) => ({
  currentUser: user.currentUser
});

const mapDispatchToProps = dispatch => ({
  setCurrentUser: user => dispatch(setCurrentUser(user))
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

in my input Form


import './TodoForm.style.css'
export class TodoForm extends Component {
    constructor(props) {
        super(props)

        this.state = {
             content : ''
        }
    }
    handleChange = (e) =>{
        this.setState({
            content: e.target.value
        })
    }
    handleSubmit =(e) =>{
        e.preventDefault();
        this.props.addTODO(this.state);
        this.setState({
            content: ''
        })
    }
    render() {
        return (
            <div className='inputTask'>
                <form onSubmit={ this.handleSubmit}>

                    <input 
                    className="textBox" 
                    type='text' 
                    onChange={ this.handleChange} 
                    value={this.state.content}
                    placeholder='what you want to do ...'
                    />
                </form>
            </div>
        )
    }
}

export default TodoForm

I have no idea How to store the react js state into localstorage. i searched on internet but unable to find the exact solution all the codes that i think is necessary post.

解决方案

Read out the localStorage item in the componentDidMount callback. Simply read the item you want to get, check if it exists and parse it to a usable object, array or datatype that need. Then set the state with the results gotten from the storage.

And to store it, simply handle it in an event handler or helper method to update both the state and the localStorage item.

class ExampleComponent extends Component {

  constructor() {
    super();
    this.state = {
      something: {
        foo: 'bar'
      }
    }
  }

  componentDidMount() {
    const storedState = localStorage.getItem('state');
    if (storedState !== null) {
      const parsedState = JSON.parse(storedState);
      this.setState({ something: parsedState });
    }
  }

  clickHandler = (event) => {
    const value = event.target.value;
    const stringifiedValue = JSON.stringify(value);
    localStorage.setItem('state', stringifiedValue);
    this.setState({ something: value });
  }

  render() {
    return (
      <button onClick={clickHandler} value={this.state.something}>Click me</button>
    );
  }

}

这篇关于如何将反应 js 状态保存到本地存储中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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