Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将react js状态保存到localstorage中_Javascript_Reactjs_React Redux_React Router_Local Storage - Fatal编程技术网

Javascript 如何将react js状态保存到localstorage中

Javascript 如何将react js状态保存到localstorage中,javascript,reactjs,react-redux,react-router,local-storage,Javascript,Reactjs,React Redux,React Router,Local Storage,我不知道如何将react js状态存储到localstorage中 import React, { Component } from 'react' import './App.css'; import { auth,createUserProfileDocument } from './firebase/firebase.utils' import { TodoForm } from './components/TodoForm/TodoForm.component' import {Todo

我不知道如何将react js状态存储到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);
import React,{Component}来自“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”导入{Redirect}
从“react redux”导入{connect}
从“./redux/user/user.actions”导入{setCurrentUser}
导出类应用程序扩展组件{
建造师(道具){
超级(道具)
this.input=React.createRef()
此.state={
待办事项:[
{id:0,内容:'Welcome Sir!',isCompleted:null},
]
}
}
todoDelete=(id)=>{
const todos=this.state.todos.filter(todo=>{
返回todo.id!==id
})
这是我的国家({
待办事项
})
}
toDoComplete=(id,isCompleted)=>{
console.log(已完成)
var todos=[…this.state.todos];
var index=todos.findIndex(obj=>obj.id==id);
todos[index].isCompleted=!isCompleted;
this.setState({todos});
console.log(已完成)
}
addTODO=(todo)=>{
todo.id=Math.random()
todo.isCompleted=true
让todos=[…this.state.todos,todo]
这是我的国家({
待办事项
})
}
unsubscribeFromAuth=null;
componentDidMount(){
const{setCurrentUser}=this.props;
this.unsubscribeFromAuth=auth.onAuthStateChanged(异步userAuth=>{
if(userAuth){
const userRef=await createUserProfileDocument(userAuth);
userRef.onSnapshot(快照=>{
setCurrentUser({
id:snapShot.id,
…snapShot.data()
});
});
}
setCurrentUser(userAuth);
});
}
组件将卸载(){
这是。unsubscribeFromAuth();
}
render(){
返回(
)
}
}
常量mapStateToProps=({user})=>({
currentUser:user.currentUser
});
const mapDispatchToProps=调度=>({
setCurrentUser:user=>dispatch(setCurrentUser(用户))
});
导出默认连接(
MapStateTops,
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

导入“./TodoForm.style.css”
导出类TodoForm扩展组件{
建造师(道具){
超级(道具)
此.state={
内容:“”
}
}
handleChange=(e)=>{
这是我的国家({
内容:e.target.value
})
}
handleSubmit=(e)=>{
e、 预防默认值();
this.props.addTODO(this.state);
这是我的国家({
内容:“”
})
}
render(){
返回(
)
}
}
导出默认格式
我不知道如何将react js状态存储到localstorage中。 我在互联网上搜索过,但找不到确切的解决方案。我认为所有的代码都是必要的。你可以用它把任何数据保存在本地存储器中

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
项。只需读取您想要获取的项,检查它是否存在,并将其解析为需要的可用对象、数组或数据类型。然后使用从存储器中获得的结果设置状态

要存储它,只需在事件处理程序或助手方法中处理它,以更新状态和
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>
    );
  }

}
类示例组件扩展组件{
构造函数(){
超级();
此.state={
一些东西:{
福:“酒吧”
}
}
}
componentDidMount(){
const storedState=localStorage.getItem('state');
if(storedState!==null){
const parsedState=JSON.parse(storedState);
this.setState({something:parsedState});
}
}
clickHandler=(事件)=>{
常量值=event.target.value;
const stringifiedValue=JSON.stringify(value);
setItem('state',stringifiedValue);
this.setState({something:value});
}
render(){
返回(
点击我
);
}
}

在本地存储中设置数据

localStorage.removeItem('key_name');
 let data = localStorage.getItem('key_name');
键值对:

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

localStorage.setItem('key_name', JSON.stringify(object));
从本地存储中删除数据

localStorage.removeItem('key_name');
 let data = localStorage.getItem('key_name');
从本地存储获取数据

localStorage.removeItem('key_name');
 let data = localStorage.getItem('key_name');
对象:

let data = JSON.parse(localStorage.getItem('key_name'));
清除本地存储(删除所有数据)


在何处写入此文件?要将哪个数据存储到localStorage?@riponAddin todos从用户处接收的对象这是否回答了您的问题@你能创建一个沙箱吗?我们可以调试。