簡體   English   中英

如何將反應js state保存到本地存儲中

[英]how to save react js state into localstorage

我不知道如何將反應 js state 存儲到本地存儲中。

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);

在我的輸入表單中


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

我不知道如何將反應 js state 存儲到本地存儲中。 我在互聯網上搜索但無法找到我認為有必要發布的所有代碼的確切解決方案。

您可以使用reactLocalStorage將任何數據保存在本地存儲中

import {reactLocalStorage} from 'reactjs-localstorage';

reactLocalStorage.set('var', true);
reactLocalStorage.get('var', true);
reactLocalStorage.setObject('var', {'test': 'test'});
reactLocalStorage.getObject('var');
reactLocalStorage.remove('var');
reactLocalStorage.clear();

讀出componentDidMount回調中的localStorage項。 只需閱讀您想要獲取的項目,檢查它是否存在並將其解析為可用的 object、數組或需要的數據類型。 然后使用從存儲中獲得的結果設置 state。

要存儲它,只需在事件處理程序或輔助方法中處理它,以更新 state 和localStorage項。

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>
    );
  }

}

在 localStorage 中設置數據

鍵值對:

localStorage.setItem('key_name',"value");

object

localStorage.setItem('key_name', JSON.stringify(object));

從 localStorage 中刪除數據

localStorage.removeItem('key_name');

從 localStorage 獲取數據

 let data = localStorage.getItem('key_name');

object:

let data = JSON.parse(localStorage.getItem('key_name'));

clear localStorage(刪除所有數據)

localStorage.clear();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM