如何将反应js状态保存到本地存储中
Posted
技术标签:
【中文标题】如何将反应js状态保存到本地存储中【英文标题】:how to save react js state into localstorage 【发布时间】:2021-11-20 19:16:21 【问题描述】:我不知道如何将 react js 状态存储到本地存储中。
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
我不知道如何将 react js 状态存储到本地存储中。 我在互联网上搜索但无法找到我认为有必要发布的所有代码的确切解决方案。
【问题讨论】:
您要将哪些数据存储到 localStorage 中? @RiponUddin todos 对象从用户那里收到 这能回答你的问题吗? Using LocalStorage with React? 【参考方案1】:您可以使用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();
【讨论】:
在哪里写这个【参考方案2】:在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>
);
【讨论】:
@DeepakBhamla 你能创建一个沙箱吗?我们可以调试了。【参考方案3】:在localStorage中设置数据
键值对:
localStorage.setItem('key_name',"value");
对象
localStorage.setItem('key_name', JSON.stringify(object));
从本地存储中删除数据
localStorage.removeItem('key_name');
从本地存储中获取数据
let data = localStorage.getItem('key_name');
对象:
let data = JSON.parse(localStorage.getItem('key_name'));
clear localStorage(删除所有数据)
localStorage.clear();
【讨论】:
以上是关于如何将反应js状态保存到本地存储中的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Vue.js + Vuex (createStore) 将“状态”变量保存到浏览器 localStorage
如何在没有 Redux 的情况下将状态保存在本地存储 React 中?